对泛型类型参数调用静态方法 [英] 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();
}
我收到一个编译时错误:
I get a compile-time error:
T"是一个类型参数",在给定的上下文中无效.
'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.
推荐答案
在这种情况下,您应该直接调用约束类型的静态方法.C#(和 CLR)不支持虚拟静态方法.所以:
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
...可以无异于:
SomeBaseClass.StaticMethodOnSomeBaseClassThatReturnsCollection
通过泛型类型参数是不需要的间接方式,因此不受支持.
Going through the generic type parameter is an unneeded indirection and hence not supported.
这篇关于对泛型类型参数调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!