日期:2014-05-20  浏览次数:20746 次

请问一个关于static的问题
我在看MSDN中的一个例子,不是很明白为什么static   void   ClassTaker(TheClass   c)
要声明成static的   我把static去掉
就报错   An   object   reference   is   required   for   the   nonstatic   field,   method,   or   property   'ConsoleApplication1.Program.ClassTaker(TheClass) 'using   System;


using   System.Collections.Generic;
using   System.Text;
using   System;

class   TheClass
{
        public   string   willIChange;

}
...

namespace   ConsoleApplication1
{
        class   Program
        {
                static   void   ClassTaker(TheClass   c)   //为什么要申明成static
                {
                        c.willIChange   =   "changed! ";
                }

                static   int   Main(string[]   args)
                {
                        TheClass   testclass   =   new   TheClass();
                        ClassTaker(testclass   );
                        return   0;
                }
        }
}


------解决方案--------------------
static表明那个方法属于其所在的类,去掉static在用到那个方法时,要先实例化.去掉static后可以这样用:
Program p=new Program()
p.ClassTaker(testclass)
------解决方案--------------------
去掉 static 就成了实例方法了
不能直接调用了
ClassTaker(testclass );

ClassTaker() 是 class Program 内的方法
你看 Program 哪里 new 了
没有
所以就只能静态调用
要静态调用 就必须是 static 的方法
------解决方案--------------------
static即静态方法,可以不用实例化该类就可调用此方法。
如System.Console.Write()。