編譯器錯誤 CS0165
使用未指派的區域變數 'name'
C# 編譯器不允許使用未初始化的變數。 如果編譯器偵測到使用可能尚未初始化之變數的情形,就會產生編譯器錯誤 CS0165。 如需詳細資訊,請參閱欄位。 即使您的特定程式碼不會導致使用未指派變數的建構,但當編譯器遇到此種建構時,就會產生這個錯誤。 這會避免明確設定的過度複雜規則。
如需詳細資訊,請參閱為何遞迴 Lambda 造成明確指派錯誤? \(英文\)。
範例 1
下列範例會產生 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();
}
}
範例 2
編譯器錯誤 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();
}
}
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應