将System.Type转换为特定类

时间:2015-01-14 12:03:36

标签: c# oop reflection casting

我使用反射获得所需的System.Type。我需要检查它是否是Component类的后代。如果是,我需要将此特定类添加到List。转换类型的正确方法是什么?

  foreach (Type curType in allTypes)
  {
     if (curType descends from Component)
       componentsList.Add( (Component)curType );
  }

3 个答案:

答案 0 :(得分:3)

您可以使用IsSubClassOf

if (typeof(Component).Equals(curType) || curType.IsSubClassOf(typeof(Component)))
{ }

尽管如此,Type仍然是类型,而不是实例,因此如果您考虑将实例添加到列表中,则应检查实例,而不是类型。

如果您有实例,最好使用is

if (instance is Component)
{ }

如果您打算创建特定类型的新实例,请使用Activator.CreateInstance

object instance = Activator.CreateInstance(curType);

答案 1 :(得分:3)

您正在寻找IsSubClassOf方法。注意:如果curTypeComponent的类型相同,则会报告为false。在这种情况下,您可能需要添加Equals支票。

if (curType.IsSubclassOf(typeof(Component)))
{
    //Do stuff
}

答案 2 :(得分:3)

无法投射某种类型,但正如您在评论中所说:

  

我需要创建所有类型的列表

因此,请创建类型为List<Type>的组件列表,并将类型添加到该列表中。

您已经检查过它们是否已从Component继承,因此只有那些类型才会在该列表中结束。

相关问题