对泛型类型参数调用静态方法 [英] Calling a static method on a generic type parameter

查看:40
本文介绍了对泛型类型参数调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望做这样的事情,但它在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆