Several days back one of my coworker ran into an issue where he wanted to call a static method on generic type parameter. The
reason behind this is that we have a hierarchy of classes with a static method defined on the base class. We also some sub class hide the base static method using the “static new” modifier. Our class hierarchy is as follows:
class Base { public static void M() { } }
class SubClass1 {}
class SubClass2 { public static new void M() { } }
In order to call the appropriate version of M depending on the type, he decided to use Generics. He knew that method cannot be called on a type parameter directly, so he added the class constraint. His function is as follows:
void GenericMethod<T> where T : Base { T.M(); }
However during compilation he got a CS0119 error: 'T' is a 'type parameter', which is not valid in the given context.
After some research I found this article saying that C# compiler and JIT compiler cannot determine the proper type during compilation.
So the syntax above violates the principle that static methods should be determine “statically”. This surprised me a little bit. I thought
C# compiler (or JIT compiler) should be able to decide the proper class to use at compilation time, because Generics are just like
"templates” in the C++ world. Am I wrong?
The correct answer is “Yes”. CLR Generics are more than “templates” – it has the concept of “code sharing”. That is to say, if you have
two generic methods instantiated by two reference types, they’ll be sharing exactly the same copy of JITted code. And the type
parameter is passed in as a parameter at runtime to the JITted method. And because of this, C# compiler as well as the JIT compiler
cannot determine T in the above code during compilation time so that it raises the CS0119 error. Joel has a great article talking about
code sharing in detail.
What an interesting thing... Make me miss C++ templates... ![]()
This article is to my girl, who shall be deep in sweet dreams now. I love you baby, as always.
本文探讨了在C#中如何调用泛型类型参数上的静态方法,并解释了为何直接调用会触发编译错误。文章通过一个具体的类层次结构示例说明了这一问题,并讨论了CLR泛型的工作原理及其与C++模板的区别。
3万+

被折叠的 条评论
为什么被折叠?



