gpt4 book ai didi

c# - 如何在 C# 中传递方法参数作为泛型接口(interface)基类型?

转载 作者:行者123 更新时间:2023-11-30 16:04:15 25 4
gpt4 key购买 nike

假设我有一个接口(interface)定义如下:

interface IContract
{
void CommonMethod();
}

然后从这个接口(interface)继承的另一个接口(interface)定义为:

interface IContract<T> : IContract where T : EventArgs
{
event EventHandler<T> CommonEvent;
}


我的具体问题是,给定任何实现 IContract 的实例, 我怎么能确定是否也是 IContract<T> ,如果是,那么 IContract<T> 的通用类型是什么?没有对 IContract<T> 的每个已知类型进行硬编码我可能会遇到。


最终,我会使用此确定来调用以下模式:

void PerformAction<T>(IContract<T> contract) where T : EventArgs
{
...
}

最佳答案

因为你需要一个 IContract<T> 的实例您必须先使用反射来获取泛型类型参数,然后再调用适当的方法:

// results in typeof(EventArgs) or any class deriving from them
Type type = myContract.GetType().GetGenericArguments()[0];

现在获取 IContract<T> 的通用类型定义并获得适当的方法。

// assuming that MyType is the type holding PerformAction
Type t = typeof(MyType).MakeGenericType(type);
var m = t.GetMethod("PerformAction");

或者如果只有方法PerforAction是通用的而不是 MyType :

// assuming that MyType is the type holding PerformAction
Type t = typeof(MyType);
var m = t.GetMethod("PerformAction").MakeGenericMethod(type);

现在您应该能够在 IContract 的实例上调用该方法了:

var result = m.Invoke(myInstance, new[] { myContract } );

在哪里myInstance类型为 MyType .

关于c# - 如何在 C# 中传递方法参数作为泛型接口(interface)基类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35309459/

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