调用一个泛型类型参数的静态方法 [英] Calling a static method on a generic type parameter
问题描述
我希望做这样的事情,但它似乎是在C#中非法的:
I was hoping to do something like this, but it appears to be illegal in C#:
public Collection MethodThatFetchesSomething<T>()
where T : SomeBaseClass
{
return T.StaticMethodOnSomeBaseClassThatReturnsCollection();
}
我得到一个编译时错误:'T'是一个'类型参数,这是不是在给定的情形下有效。
I get a compile-time error: "'T' is a 'type parameter', which is not valid in the given context."
给出一个泛型类型参数,我怎么能叫上泛型类的静态方法?静态方法必须是可用的,给定的约束
Given a generic type parameter, how can I call a static method on the generic class? The static method has to be available, given the constraint.
推荐答案
在这种情况下,你应该呼吁直接constrainted类型的静态方法。 C#(和CLR)不支持虚拟静态方法。所以T.StaticMethodOnSomeBaseClassThatReturnsCollection不能超过SomeBaseClass.StaticMethodOnSomeBaseClassThatReturnsCollection不同。通过泛型类型参数会是一个不需要间接,因此不支持。
In this case you should just call the static method on the constrainted type directly. C# (and the CLR) do not support virtual static methods. So T.StaticMethodOnSomeBaseClassThatReturnsCollection can be no different than SomeBaseClass.StaticMethodOnSomeBaseClassThatReturnsCollection. Going through the generic type parameter is an unneeded indirection and hence not supported.
这篇关于调用一个泛型类型参数的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!