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
.