简体   繁体   English

动态和显式通用接口实现

[英]Dynamic and Explicit Generic Interface Implementation

I've learnt from here that dynamic variables cannot access methods on interfaces they explicitly implement. 我从这里了解到,动态变量无法访问它们明确实现的接口上的方法。 Is there an easy way to invoke the interface methods when I don't know the type parameter T at compile time? 当我在编译时不知道类型参数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
}      

I don't know the type parameter T , so (as far as I know) I can't cast my dynamic variable x . 我不知道类型参数T ,所以(据我所知)我无法转换动态变量x I have lots of methods in the interface, so don't really want to create corresponding DoXXX() pass through methods. 我的界面中有很多方法,所以真的不想创建相应的DoXXX()直通方法。

Edit: Note that I don't control and cannot change C or I . 编辑:请注意,我无法控制并且无法更改CI

You can do this via reflection: 您可以通过反射来做到这一点:

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 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM