首页 > 解决方案 > “检测到无法访问的代码”和“当前上下文中不存在名称”错误

问题描述

我的大部分代码看起来都很好,但是当我尝试运行它时,它显示构建失败,它在“Console.Write(B[j]);”中的 j 下面显示一个问题标记,它显示“检测到无法访问的代码”它,它还显示:名称'j'在当前上下文中不存在。它有什么问题?

 static void Function(int[]A, int[] B)
    {

        for (int i = 0; i < A.Length; i++)
        {
            for (int j = 0; j < B.Length; j++)
            {
                if (A[i] == B[j])
                {

                    continue;
                }
            } continue;
            Console.Write("the same number in both arrays is:");
            Console.WriteLine(A[i]);

            Console.Write("the location of number in the arrays is:");
            Console.Write(A[i]);
            Console.Write(B[**j**]);
        } 

    }   

    static void Main(string[] args)
    {
        int[] A = new int[] { 5, 4, 3, 2 };
        int[] B = new int[] { 9, 8, 2, 6 };

        Function(A, B);
    }
}

标签: c#

解决方案


您的编译器试图告诉您的是Console.WriteLine后面的语句continue;不可访问。

continue将跳回到循环的开头并直接开始循环的下一次迭代,忽略循环体中通常会在它之后执行的所有指令。

continueC# 文档中有一个很好的例子: https ://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/continue

从您的代码中,我假设您想找到两个数组中的一个数字并打印它。如果这就是你想要完成的,你可以这样做:
你可以在这个 dotnet Fiddle中尝试

public class Program
{
    static void Function(int[]A, int[] B)
    {

        for (int i = 0; i < A.Length; i++)
        {
            for (int j = 0; j < B.Length; j++)
            {
                if (A[i] == B[j])
                {
                    Console.Write("the same number in both arrays is: ");
                    Console.WriteLine(A[i]);

                    Console.Write("the location of number in the arrays is: ");
                    Console.Write($"A[{i}] ");
                    Console.Write($"B[{j}]");
                    return;
                }
            }
        } 

        // could not find two equal numbers
        Console.WriteLine("There are no equal numbers in the array.");
    }   

    static void Main(string[] args)
    {
        int[] A = new int[] { 5, 4, 3, 2 };
        int[] B = new int[] { 9, 8, 2, 6 };

        Function(A, B);
    }
}

这样循环将一直运行,直到找到两个数组中的匹配项。

  • 一旦找到匹配项,它将打印到控制台。
    return;语句使函数立即停止执行并返回给它的调用者(Main在这种情况下)
  • 如果在两个数组中都找不到匹配项,则循环将结束并Console.WriteLine调用最后一个。

推荐阅读