编译器错误 CS0103
当前上下文中不存在名称“identifier”
尝试了使用类、命名空间或范围中不存在的名称。 检查名称的拼写,并检查 using
指令和程序集引用,确保您尝试使用的名称可用。
如果在循环或者 try
或 if
块中声明一个变量,然后尝试从封闭代码块或独立代码块访问此变量,通常就会发生此错误,如下面的示例所示:
注意
如果表达式 lambda 中缺少运算符 =>
中的 greater than
符号,也可能出现此错误。 有关详细信息,请参阅表达式 lambda。
using System;
class MyClass1
{
public static void Main()
{
try
{
// The following declaration is only available inside the try block.
var conn = new MyClass1();
}
catch (Exception e)
{
// The following expression causes error CS0103, because variable
// conn only exists in the try block.
if (conn != null)
Console.WriteLine("{0}", e);
}
}
}
下面的示例解决了这一错误:
using System;
class MyClass2
{
public static void Main()
{
// To resolve the error in the example, the first step is to
// move the declaration of conn out of the try block. The following
// declaration is available throughout the Main method.
MyClass2 conn = null;
try
{
// Inside the try block, use the conn variable that you declared
// previously.
conn = new MyClass2();
}
catch (Exception e)
{
// The following expression no longer causes an error, because
// the declaration of conn is in scope.
if (conn != null)
Console.WriteLine("{0}", e);
}
}
}