Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态和显式通用接口实现_C#_Generics_Dynamic_Explicit Interface - Fatal编程技术网

C# 动态和显式通用接口实现

C# 动态和显式通用接口实现,c#,generics,dynamic,explicit-interface,C#,Generics,Dynamic,Explicit Interface,我从中学到,动态变量无法访问它们显式实现的接口上的方法。当我在编译时不知道类型参数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
时,有没有一种简单的方法来调用接口方法

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
{
无效方法1(T);
}
C班:I
{   
无效I.Method1(T)
{ 
控制台写入线(t);
}
}
静态空隙法1(I,T)
{
i、 方法1(t);
}
void Main()
{
I=新的C();
动态x=i;
DoMethod1(x,1);//这很有效
((I)x).Method1(2);//这也是
x、 方法1(3);//这不正确
}      
我不知道类型参数
t
,因此(据我所知)我无法强制转换我的动态变量
x
。我在接口中有很多方法,所以我真的不想创建相应的
DoXXX()
pass-through方法


编辑:请注意,我不控制也不能更改
C
I

您可以通过反射来执行此操作:

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 });
I=newc();
动态x=i;//您不必使用dynamic。对象也会起作用。
var methodInfo=x.GetType().GetInterfaces()[0].GetMethod(“Method1”);
调用(x,新对象[]{3});

我可能可以用反射做一些事情,但是类型
C
实现了多个通用接口,并且有些方法有各种重载,所以这并不容易。