作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
说明我的问题的最佳方式是使用此示例代码:
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/
我是一名优秀的程序员,十分优秀!