再谈static在C++和C#中的不同处理

先看这段C#代码

    public class C 
        
public static void M() 
            Console.WriteLine(
"call in class C"); 
        }
 
    }

    
    
public class D : C 
        
public new static void M() 
            Console.WriteLine(
"call in class D"); 
        }
 
    }

    
    
public class E<T> where T : C 
        
public static void N() 
            T.M(); 
        }
 
    }

代码是错误的,不允许一个instance来call一个static method。如果你编译的话,会提示:
Error 2 'T' is a 'type parameter', which is not valid in the given context

为什么?
从语言设计的角度来看,针对上面的代码,下面的三种情况只能有一种为true。
1. 本身就是错误的写法
2. E.N() calls C.M() no matter what T is.
3. E.N() calls C.M() but E.N() calls D.M().

如果按照2设计,会有用户期望当T是class D的时候,执行class D的method M,而不是C。Static之所以是static,因为它在编译时刻就可以被确切的determined,或者说,在静态代码分析阶段,这个方法就可以被确定了。所以,如果按照3的方式来设计,我们就违背了这个原则。
这样,只有1了。

另外的解释:
1. virtual static,为什么没这个东西?
2. 没有this指针而已
(以上内容转自同事的一个blog,做了简单的修改)

不过,不清楚C++里面为什么允许这么做?
public class Test{
    
public static void Say(){}
}


Test t;
Test
* t2 = new Test();

t.Say();
t2
->Say();
posted @ 2007-10-29 16:34  鞠强  阅读(2343)  评论(8编辑  收藏  举报

hello

world