如何调用泛型方法与类型约束时,参数没有这些限制? [英] How to call a generic method with type constraints when the parameter doesn't have these constraints?
问题描述
class A { }
interface I { }
void GenericStuff<T>(T x) { }
void SpecificStuff<T>(T x) where T : A, I { }
void Start<T>(T x)
{
if (x is A && x is I)
SpecificStuff(x); // <---- Wrong type
else
GenericStuff(x);
}
我已经得到了上面显示的情况。在方法开始()
我得到一个参数 X
,并根据它的类型我想打电话给任 GenericStuff()
或 SpecificStuff()
方法。当然,类型约束$ P $这样做pvent我,因为有两个人,我不能让他们身边通过铸造。
I've got the situation illustrated above. In method Start()
I get a single parameter x
and depending on it's type I want to call either the GenericStuff()
or the SpecificStuff()
method. Naturally, the type constraints prevent me from doing so, and since there are two of them, I cannot get around them by casting.
有什么办法(反射短)来完成这项工作?
Is there any way (short of reflection) to accomplish this?
推荐答案
您可以使用动态
。虽然这或多或少是荣耀的反映,它看起来更漂亮:
You can use dynamic
. While this is more or less glorified reflection, it looks much nicer:
void Start<T>(T x)
{
if (x is A && x is I)
SpecificStuff((dynamic)x);
else
GenericStuff(x);
}
请注意:
如果在以后,你改变 SpecificStuff
的类型约束,以包含第三个界面,你忘了更新你的如果
因此,您将获得运行时异常,而不是编译时错误。
Please note:
If, at a later point, you change the type constraints of SpecificStuff
to contain a third interface and you forget to update your if
accordingly, you will get runtime exceptions and not compile time errors.
这篇关于如何调用泛型方法与类型约束时,参数没有这些限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!