静态方法就像C++,VB中的全局方法谁都可以调用,但调用之前要加类名作前缀

解决方案 »

  1.   

    to liss,所有程序将被编译成IL再被CLR执行,而IL的运行机构是基于堆栈。因为上面的程序更改的函数参数将会被不同的线程放在各自的堆栈里进行运算,然后返回,因此不会出现你所说的情况。
      

  2.   

    静态方法不被对象调用,而被类调用!
    例如:
    class Math
    {
    public static double Sin(double d){....}
    }
    double d = Math.Sin(22);double f = Math.Sin(33);
    所得结果肯定不同!!
      

  3.   

    我想,liss问的问题是在多线程的情况,而不是如何调用static method。其实,自己写个程序试验一下就明白了。using System;
    using System.Threading;class a
    {
         // should declare static before return type
         public static int add(int i) { 
              // if use i++, the value will not be incremented before returning
              return ++i; 
         }     public static void workerMethod() {
            while (true) {
        Console.WriteLine("{0}", a.add(5));
            }
         }     public static void Main(String[] args) {
            for (int i=0; i<5; i++) {
                 ThreadStart worker = new ThreadStart(workerMethod);
        Thread workerThread = new Thread(worker);
        workerThread.Start();
            }
         }
    }结果是不断显示6。首先,你的例子里i是函数传递参数,pass by value,就肯定不会出现你所说的后果。用ILDasm看add(int i)的IL码,应该就能明白了。.method public hidebysig static int32  'add'(int32 i) cil managed
    {
      // Code size       11 (0xb)
      .maxstack  2
      .locals init (int32 V_0)
      IL_0000:  ldarg.0
      IL_0001:  ldc.i4.1
      IL_0002:  add
      IL_0003:  dup
      IL_0004:  starg.s    i
      IL_0006:  stloc.0
      IL_0007:  br.s       IL_0009
      IL_0009:  ldloc.0
      IL_000a:  ret
    } // end of method a::'add'BTW,关于i++语句。因为IL是被JIT到本地机器码执行,所以某些情况下还要看运行的机器和JIT编译器。i++这个语句,应该是由两个机器指令执行的,一个加法,一个存储。因此当运行的机器是多CPU的时候,有可能因为Context Switch,造成预期外的结果。.NET Framework怎么处理这个,我就不大清楚了。