ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Compiler Error CS0165 使用了未赋值的局部变量“name” C# 编译器不允许使用未初始化的变量。如果编译器检测到使用了可能未初始化的变量,就会生成 编译错误CS0165。有关详细信息,请参阅[字段(C# 编程指南)](https://msdn.microsoft.com/zh-cn/library/ms173118.aspx)。请注意,当编译器遇到可能会导致使用未赋值变量的构造时,即使您的特定代码不会使用该变量,也会生成此错误。这样可以避免对明确赋值使用过度复杂的规则。 有关更多信息,请参见 [http://blogs.msdn.com/ericlippert/archive/2006/08/18/706398.aspx](http://blogs.msdn.com/ericlippert/archive/2006/08/18/706398.aspx)。 下面的示例生成 CS0165: ``` // CS0165.cs using System; class MyClass { public int i; } class MyClass2 { public static void Main(string[] args) { // i and j are not initialized. int i, j; // You can provide a value for args[0] in the 'Command line arguments' // text box on the Debug tab of the project Properties window. if (args[0] == "test") { i = 0; } // If the following else clause is absent, i might not be // initialized. //else //{ // i = 1; //} // Because i might not have been initialized, the following // line causes CS0165. j = i; // To resolve the error, uncomment the else clause of the previous // if statement, or initialize i when you declare it. // The following example causes CS0165 because myInstance is // declared but not instantiated. MyClass myInstance; // The following line causes the error. myInstance.i = 0; // To resolve the error, replace the previous declaration with // the following line. //MyClass myInstance = new MyClass(); } } ``` 编译器错误 CS0165 在递归委托定义来生成。可以通过在以下两个语句中定义委托可避免此错误,以便在变量初始化之前,不使用变量。下面的示例演示错误和解决方案。 ``` class Program { delegate void Del(); static void Main(string[] args) { // The following line causes CS0165 because variable d is used // as an argument before it has been initialized. Del d = delegate() { System.Console.WriteLine(d); }; //// To resolve the error, initialize d in a separate statement. //Del d = null; //// After d is initialized, you can use it as an argument. //d = delegate() { System.Console.WriteLine(d); }; //d(); } } ```