静态方法问题

时间:2014-08-22 13:08:53

标签: c#

我有一个问题,如果在所有可能的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;
                }
            }
        }

2 个答案:

答案 0 :(得分:7)

static方法不属于任何实例。他们属于班级本身。您需要指定您的班级名称才能调用Do方法。

有关静态实例方法的详细信息,请参阅文档:

答案 1 :(得分:0)

由于该方法是静态的,因此只有一个方法,而不是每个实例的方法。您可以使用类调用静态方法:

Console.WriteLine(Dog.Do(42));
相关问题