gpt4 book ai didi

c# - 如何将对象的类型与泛型类型进行比较,与泛型参数无关?

转载 作者:可可西里 更新时间:2023-11-01 08:34:11 25 4
gpt4 key购买 nike

说明我的问题的最佳方式是使用此示例代码:

  class Item {}
class Container< T > {}
class Program
{
static void DoSomething( object something )
{
if( typeof( Item ) == something.GetType() )
{
System.Console.WriteLine( "Item" );
}
else if( typeof( Container<> ) == something.GetType() )
{
System.Console.WriteLine( "Container<>" );
}
}

static void Main( string[] args )
{
DoSomething( new Item() );
DoSomething( new Container< int >() );
}
}

以下行将不起作用:

else if( typeof( Container<> ) == something.GetType() )

是否可以在不显式更改 Container<> 的情况下使其工作?进入Container<int> ?我想知道那个对象是“容器”类型的,我真的不感兴趣是吗 Container<int>Container<string> .除了几十行反射之外还有什么提示吗?

最佳答案

尝试:

typeof(Container<>) == something.GetType().GetGenericTypeDefinition()

请注意,只有在实际类型为 Container<T> 时才会返回 true .它不适用于派生类型。例如,它将返回 false对于以下内容:

class StringContainer : Container<string>

如果您需要使其适用于这种情况,您应该遍历继承层次结构并测试每个基类是否为 Container<T> :

static bool IsGenericTypeOf(Type genericType, Type someType)
{
if (someType.IsGenericType
&& genericType == someType.GetGenericTypeDefinition()) return true;

return someType.BaseType != null
&& IsGenericTypeOf(genericType, someType.BaseType);
}

关于c# - 如何将对象的类型与泛型类型进行比较,与泛型参数无关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1855238/

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