Compiler Error CS0103

当前上下文中不存在名称“identifier”

尝试使用类、命名空间或范围中不存在的名称。检查名称的拼写,并检查 正在使用的目录和程序集引用,确保您尝试使用的名称可用。

如果在循环或者 tryif 块中声明一个变量,然后尝试从封闭代码块或一独立代码块访问此变量,经常会发生此错误。如下面的示例所示。

using System;

class MyClass1
{
    public static void Main()
    {
        try
        {
            // The following declaration is only available inside the try block.
            MyClass1 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);
        }
    }
}