Cannot call static method on type parameter, even with class constraint

来源:互联网 发布:vscode调试html插件 编辑:程序博客网 时间:2024/04/30 10:59

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... smile_nerd

This article is to my girl, who shall be deep in sweet dreams now. I love you baby, as always.

Technorati Tags: C#,programming
原创粉丝点击