这是中文的MSDN非静态的字段、方法或属性“member”要求对象引用在方法外声明的变量与使用它的方法需要具有相同的静态声明。下面的示例生成 CS0120:// CS0120_1.cs
public class clx
{
public int i; // not static public static void Main()
{
} public static void f()
{
i = 9; // CS0120, in a static method
// try the following lines instead
// clx Myclx = new clx();
// Myclx.i = 9;
}
}
有来自静态方法的非静态方法调用,也将生成 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
// MyClass anInstanceofMyClass = new MyClass();
// anInstanceofMyClass.TestCall();
} public void TestCall()
{
}
}
同样,静态方法不能调用实例方法,除非显式给它提供了类的实例。例如,下面的示例也生成 CS0120:// CS0120_3.cs
using System;public class x
{
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);
}
}
public class clx
{
public int i; // not static public static void Main()
{
} public static void f()
{
i = 9; // CS0120, in a static method
// try the following lines instead
// clx Myclx = new clx();
// Myclx.i = 9;
}
}
有来自静态方法的非静态方法调用,也将生成 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
// MyClass anInstanceofMyClass = new MyClass();
// anInstanceofMyClass.TestCall();
} public void TestCall()
{
}
}
同样,静态方法不能调用实例方法,除非显式给它提供了类的实例。例如,下面的示例也生成 CS0120:// CS0120_3.cs
using System;public class x
{
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);
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货