gpt4 book ai didi

c# - 动态和显式通用接口(interface)实现

转载 作者:太空宇宙 更新时间:2023-11-03 15:42:40 24 4
gpt4 key购买 nike

我从here中学到了动态变量不能访问它们显式实现的接口(interface)上的方法。当我在编译时不知道类型参数 T 时,有没有一种简单的方法来调用接口(interface)方法?

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。我在接口(interface)中有很多方法,所以真的不想创建相应的 DoXXX() 传递方法。

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

最佳答案

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

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# - 动态和显式通用接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29654843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com