gpt4 book ai didi

c# - 为什么参数化通用接口(interface)的 GetMethods() 返回非参数化 MethodInfo

转载 作者:太空狗 更新时间:2023-10-30 01:36:16 24 4
gpt4 key购买 nike

给定这些接口(interface):

public interface IGenericBase<T>
{
T MyMethod<T>(T arg1);
}

public interface IGenericDescendant : IGenericBase<int>
{
}

使用 IGenericDescendant 类型,我通过 GetInterfaces() 获取接口(interface)集。正如预期的那样,这将返回一个“已解析”(参数化)类型:IGenericBase`1,其中 T 解析为 Int32。然后,我在所述接口(interface)类型上调用 GetMethods,希望得到一个类似解析的 MyMethod 版本,但我得到的是带有 T 作为未解析类型参数的通用版本。

var type = typeof(IGenericDescendant);    
foreach (var super in type.GetInterfaces())
{
foreach (var member in super.GetMethods())
{
yield return member; // Get MyMethod<T> not MyMethod<Int32>
}
}

根据微软的 documentation ,这不是 GetMethods() 的正确行为:

If the current T:System.Type represents a constructed generic type, this method returns the MethodInfo objects with the type parameters replaced by the appropriate type arguments

不幸的是,当谈到类型解析的通用接口(interface)时,情况似乎并非如此。

作为变通方法,我可以使用 MakeGenericType() 来解析类型参数,但我必须知道类型,这意味着我基本上必须通过向上遍历来按名称自己解析类型参数层次结构。对于这个具体示例来说这很容易,但我需要一个通用的解决方案。我肯定遗漏了一些明显的东西。

最佳答案

MyMethod 是在泛型接口(interface)中声明的泛型方法。如果您为泛型类型指定参数,它仍然是一个泛型方法。例如:

IGenericDescendant x = new SomeImplementation();
x.MyMethod<string>("abc"); // method is still generic

IGenericBase<int> y = new SomeOtherImplementation();
y.MyMethod<string>("abc"); // still can do that

您可能想将接口(interface)声明为

public interface IGenericBase<T>
{
T MyMethod(T arg1);
}

关于c# - 为什么参数化通用接口(interface)的 GetMethods() 返回非参数化 MethodInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22675583/

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