2

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?

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. I have lots of methods in the interface, so don't really want to create corresponding DoXXX() pass through methods.

Edit: Note that I don't control and cannot change C or I.

4

1 回答 1

0

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

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 });
于 2015-04-15T16:06:37.860 回答