【问题标题】:Dynamic and Explicit Generic Interface Implementation动态和显式的通用接口实现
【发布时间】: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()直通方法。

编辑:请注意,我无法控制也无法更改 CI

【问题讨论】:

    标签: c# generics dynamic explicit-interface


    【解决方案1】:

    你可以通过反射来做到这一点:

    I<int> i = new C<int>();
    dynamic x = i; // you dont have to use dynamic. object will work as well.
    var methodInfo = x.GetType().GetInterfaces()[0].GetMethod("Method1");
    methodInfo.Invoke(x, new object[] { 3 });
    

    【讨论】:

    • 我大概可以用反射来做点什么,但是C这个类型实现了多个泛型接口,而且有些方法有各种重载,所以并不容易。
    猜你喜欢
    • 2011-01-13
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    相关资源
    最近更新 更多