gpt4 book ai didi

c# 测试对象是否使用 .GetType().GetInterface(typeof(ISurface<>).FullName) 实现任何类型的 ISurface

转载 作者:行者123 更新时间:2023-11-30 17:02:27 24 4
gpt4 key购买 nike

我有一个插件架构,我需要检测所有实现接口(interface) ISurface<T> 的插件任何类型(即测试 ISurface<> )。我看到这里有一些使用 LINQ 的建议(例如 this one ),我想知道是否有理由支持它:

.GetType().GetInterface("ISurface`1")

编辑:关于对接口(interface)名称进行硬编码,我认为如果直接从实际接口(interface)中提取名称,这些问题就会得到缓解,正如蒂姆在下面提到的那样:

.GetType().GetInterface(typeof(ISurface<>).FullName)

.FullName 命名空间歧义也应该没有问题。除了硬编码,我主要对方法本身感兴趣,因为它看起来比通过一系列类型属性检查/LINQ 语法更短、更清晰。再一次,我不知道引擎盖下发生了什么。

最佳答案

以下是您将如何提取类型为 ISurface<anything> 的所有受支持接口(interface)的方法:

void Main()
{
var supportedInterfaces =
from intf in typeof(Test).GetInterfaces()
where intf.IsGenericType
let genericIntf = intf.GetGenericTypeDefinition()
where genericIntf == typeof(ISurface<>)
select intf;

supportedInterfaces.Dump();
}

public class Test : ISurface<int>
{
}

public interface ISurface<T>
{
}

您可以在 LINQPad 中对此进行测试(.Dump() 扩展方法是 LINQPad 扩展)。

关于c# 测试对象是否使用 .GetType().GetInterface(typeof(ISurface<>).FullName) 实现任何类型的 ISurface<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19775080/

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