【发布时间】:2015-04-15 15:46:48
【问题描述】:
我从here 了解到动态变量无法访问它们显式实现的接口上的方法。当我在编译时不知道类型参数T时,有没有一种简单的方法可以调用接口方法?
interface I<T>
{
void Method1(T t);
}
class C<T> : I<T>
{
void I<T>.Method1(T t)
{
Console.WriteLine(t);
}
}
static void DoMethod1<T>(I<T> i, T t)
{
i.Method1(t);
}
void Main()
{
I<int> i = new C<int>();
dynamic x = i;
DoMethod1(x, 1); //This works
((I<int>)x).Method1(2); //As does this
x.Method1(3); //This does not
}
我不知道类型参数T,所以(据我所知)我不能转换我的动态变量x。我的接口有很多方法,所以不想创建对应的DoXXX()直通方法。
编辑:请注意,我无法控制也无法更改 C 或 I。
【问题讨论】:
标签: c# generics dynamic explicit-interface