如何将对象的类型与泛型类型进行比较,与泛型参数无关? [英] How to compare object's type with a generics type, irrelevant to generic argument?

查看:89
本文介绍了如何将对象的类型与泛型类型进行比较,与泛型参数无关?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Item {} 
class Container< p> 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(新容器< int>());


以下行不起作用:

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

是不是将 Container<> 改为集装箱< INT> ?我想知道这个对象是'容器'类型,我真的没有兴趣是它 Container< int> 或 Container< string> code>。

解决方案

试试:



<$ p> typeof(Container<>)== something.GetType()。GetGenericTypeDefinition()

请注意,如果实际类型为 Container< T> ,则这只会返回true。它不适用于派生类型。例如,它会为以下内容返回 false

  class StringContainer:容器< string> 

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

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

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


Best way to illustrate my question is with this example code:

  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 >() );
    }
  }

The following line will not work:

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

Is it a way to make it work without explicitly changing Container<> into Container<int>? I want to know that object is of 'Container' type and I really has no interest is it Container<int> or Container<string>. Any hints other than dozens lines of reflection?

解决方案

Try:

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

Note that this will only return true if the actual type is Container<T>. It doesn't work for derived types. For instance, it'll return false for the following:

class StringContainer : Container<string>

If you need to make it work for this case, you should traverse the inheritance hierarchy and test each base class for being 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);
}

这篇关于如何将对象的类型与泛型类型进行比较,与泛型参数无关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆