我有一个问题,如果在所有可能的Dog实例上共享静态方法Do,为什么我的其他实例无法使用Do方法更改内部值或者看到所有实例的值都相同?
class Program
{
static void Main(string[] args)
{
Console.WriteLine("First value: " + Dog.Do(0));
Console.WriteLine("After first change: " + Dog.Do(5));
Dog dog1 = new Dog();
Dog dog2 = new Dog();
//cant use why ? i want to see from other instances of Dog about value either k is same for all instances
//dog1.Do(44);
//Console.Writeline(dog2.Do(0));
Console.ReadLine();
}
public class Dog
{
public static int Do(int t)
{
int k = 3;
k = k + t;
return k;
}
public int Do2()
{
return 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
static方法不属于任何实例.他们属于班级本身.您需要指定您的类名称来调用Do方法.
有关静态和实例方法的更多信息,请参阅文档: