如何确定如果对象是其基本泛型类型? [英] How to Identify If Object Is Of A Base Generic Type?

查看:108
本文介绍了如何确定如果对象是其基本泛型类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类

DataMapper<TDalType, TFieldType> : DataMapperBase

有关具体的实体,我有一个

For a particular entity, I have a

ObjectADataMapper<TFieldType> : DataMapper<ObjectADal, TFieldType>



然后我有一个DataMapperBase的实例,并需要确定它是否是一个版本的实体ObjectADataMapper(有TFieldType的任意值)。

I then have an instance of a DataMapperBase and need to determine if it is an entity that is a version of ObjectADataMapper (with any value of TFieldType).

推荐答案

如果对象的类型是通用的,如果你可以看到检查此相应的通用模板是您正在寻找的通用模板。例如:

You can check this by seeing if the object's type is generic and if the corresponding generic template is the generic template that you are looking for. For example:

var type = obj.GetType();
bool isObjectADataMapper = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ObjectADataMapper<>);

或者,在一个可重用的方式

Or, in a reusable way

  bool IsInstanceOfGenericTypeClosingTemplate(object obj, Type genericTypeDefinition){ 
      if(obj == null) throw new ArgumentNullException("obj");
      if(genericTypeDefinition== null) throw new ArgumentNullException("genericTypeDefinition");
      if(!genericTypeDefinition.IsGenericTypeDefinition) throw new ArgumentException("Must be a generic type definition.", "genericTypeDefinition");
      Type type = obj.GetType(); 
      return type.IsGenericType && type.GetGenericTypeDefinition() == genericTypeDefinition;
  }

您甚至可以借此进一步,看看类型由通用派生问题类型定义。例如,假设你有:

You could even take this further and see if the type is derived from the generic type definition in question. For example, consider that you have:

  public class StringDataMapper : ObjectADataMapper<string>
  { 
     // .... whatever
  }



在这种情况下,我提供的方法将失败。所以,你必须做这样的事情。

In this case the method I provided would fail. So you'd have to do something like

  bool IsInstanceOfGenericTypeClosingTemplateOrSubclassThereof(object obj, Type genericTypeDefinition){ 
      if(obj == null) throw new ArgumentNullException("obj");
      if(genericTypeDefinition== null) throw new ArgumentNullException("genericTypeDefinition");
      if(!genericTypeDefinition.IsGenericTypeDefinition) throw new ArgumentException("Must be a generic type definition.", "genericTypeDefinition");

      Type type = obj.GetType();
      while ( type != typeof(object) )
      {
         if(type.IsGenericType && type.GetGenericTypeDefinition() == genericTypeDefinition) 
         {
            return true;
         }
         type = type.BaseType;
      } 
      return false;
  }

这篇关于如何确定如果对象是其基本泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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