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

本文探讨了在C#中如何调用泛型类型参数上的静态方法,并解释了为何直接调用会触发编译错误。文章通过一个具体的类层次结构示例说明了这一问题,并讨论了CLR泛型的工作原理及其与C++模板的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值