c# - “检测到无法访问的代码”和“当前上下文中不存在名称”错误
问题描述
我的大部分代码看起来都很好,但是当我尝试运行它时,它显示构建失败,它在“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);
}
}
解决方案
您的编译器试图告诉您的是Console.WriteLine
后面的语句continue;
不可访问。
continue
将跳回到循环的开头并直接开始循环的下一次迭代,忽略循环体中通常会在它之后执行的所有指令。
continue
C# 文档中有一个很好的例子: 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
调用最后一个。
推荐阅读
- python-3.x - 第一次访问时初始化python模块属性并确保原子性
- sql - SQL:如何将子查询添加到查询中
- r - 以tidyverse方式更改列中的多个值
- java - 在 Apache Camel 中基于命名空间区分 XML
- javascript - 将 dom 元素的内容存储在对象内
- javascript - 订阅者在 Angular 8+ 中完成后如何调用函数
- datetime - SOAP UI 如何定义任何日期 - 表达式
- java - 使用 Java 读取 JSON 文件
- docusignapi - 从模板创建信封时如何应用模板 setAnchorXOffset?
- java - "errorMessage": "在类 com.persi.Student.App 上找不到名为 handleRequest 且具有适当方法签名的公共方法"