如何识别对象是否为基本通用类型?

时间:2013-05-03 20:15:08

标签: c# generics inheritance

我上课了。

DataMapper<TDalType, TFieldType> : DataMapperBase

对于某个特定实体,我有一个

ObjectADataMapper<TFieldType> : DataMapper<ObjectADal, TFieldType>

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

3 个答案:

答案 0 :(得分:6)

您可以通过查看对象的类型是否为通用以及相应的通用模板是否是您要查找的通用模板来检查此问题。例如:

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

或者,以可重复使用的方式

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

您甚至可以更进一步,看看该类型是否来自相关的泛型类型定义。例如,请考虑您:

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

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

这样的事情
  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;
  }

答案 1 :(得分:0)

你需要获得类似的实例:

var typeToTestFor = typeof(ObjectADataMapper<>);

和被测对象的泛型类型

var typeOfObject being tested = objectBeingTested.GetType().GetGenericTypeDefinition();

你可以一起做下面的事情

public bool IsObjectADataMapper(DataMapperBase base) {
  var typeUnderTest = base.GetType();
  if (!typeUnderTest.IsGenericType())
    return false; // its not generic so it can't match
  var typeToTestFor = typeof(ObjectADataMapper<>);
  return typeToTestFor.Equals(typeUnderTest.GetGenericTyepDefinition());
}

答案 2 :(得分:-1)

您可以使用is

if(obj is DataMapper)
{

}