編譯器錯誤 CS0120
更新:2007 年 11 月
錯誤訊息
非靜態欄位、方法或屬性 'member' 需要物件參考
若要使用非靜態欄位、方法或屬性 (Property),您必須先建立物件執行個體 (Instance)。如需靜態方法的詳細資訊,請參閱靜態類別和靜態類別成員 (C# 程式設計手冊)。如需建立類別之執行個體的詳細資訊,請參閱執行個體建構函式 (C# 程式設計手冊)。
下列範例會產生 CS0120:
// CS0120_1.cs
public class MyClass
{
// Non-static field
public int i;
// Non-static method
public void f(){}
// Non-static property
int Prop
{
get
{
return 1;
}
}
public static void Main()
{
i = 10; // CS0120
f(); // CS0120
int p = Prop; // CS0120
// try the following lines instead
// MyClass mc = new MyClass();
// mc.i = 10;
// mc.f();
// int p = mc.Prop;
}
}
如果是呼叫靜態方法中的非靜態方法,也會產生 CS0120,如下所示:
// CS0120_2.cs
// CS0120 expected
using System;
public class MyClass
{
public static void Main()
{
TestCall(); // CS0120
// To call a non-static method from Main,
// first create an instance of the class.
// Use the following two lines instead:
// MyClass anInstanceofMyClass = new MyClass();
// anInstanceofMyClass.TestCall();
}
public void TestCall()
{
}
}
同樣地,除非您明確地提供類別的執行個體,否則靜態方法不能呼叫執行個體方法 (Instance Method),如下所示:
// CS0120_3.cs
using System;
public class MyClass
{
public static void Main()
{
do_it("Hello There"); // CS0120
}
private void do_it(string sText)
// You could also add the keyword static to the method definition:
// private static void do_it(string sText)
{
Console.WriteLine(sText);
}
}