gpt4 book ai didi

c# - 有没有办法确定泛型类型是否是从特定的泛型类型定义构建的?

转载 作者:太空狗 更新时间:2023-10-30 00:09:03 25 4
gpt4 key购买 nike

我有一个通用方法:

Func<IEnumerable<T>, bool> CreateFunction<T>()

其中 T 可以是任意数量的不同类型。这个方法使用反射做了一堆事情,如果 T 是一个 IDictionary,不管字典的 TKeyTValue 我需要执行特定于字典的代码。

因此可以调用该方法:

var f = CreateFunction<string>();
var f0 = CreateFunction<SomePocoType>();
var f1 = CreateFunction<IDictionary<string,object>>();
var f2 = CreateFunction<Dictionary<string,object>>();
var f3 = CreateFunction<SomeDerivedDictionaryType<string,object>>();

等等

根据@Andy 的回答澄清

最终我想知道 T 是否继承/实现 IDictionary 即使 T 本身是 Dictionary 或者从该接口(interface)派生的一些其他类型。

if(typeof(T) == typeof(IDictionary<,>)

不起作用,因为 T 是泛型类型而不是泛型类型定义。

在不知道 TKeyTValue(在编译时不知道)的情况下,我无法与直到运行时才知道的任何具体类型进行比较.

我唯一想到的是查看类型的名称或通过反射检查其方法,寻找让我相信它是字典的方法(即寻找 ContainsKeyget_Item)。

是否有任何直接的方法可以做出这种决定?

最佳答案

您可以使用 IsGenericType 避免使用丑陋且有潜在风险的类型名称字符串检查和 GetGenericTypeDefinition成员,如下:

var type = typeof (T);
if (typeof (IDictionary).IsAssignableFrom(type))
{
//non-generic dictionary
}
else if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof (IDictionary<,>))
{
//generic dictionary interface
}
else if (type.GetInterfaces().Any(
i => i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof (IDictionary<,>)))
{
//implements generic dictionary
}

关于c# - 有没有办法确定泛型类型是否是从特定的泛型类型定义构建的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3765859/

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