转换系统.键入特定类



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

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

进行某种类型的转换,但正如您在评论中所说:

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

因此,将您的组件列表设置为类型 List<Type> ,并将类型添加到该列表中。

您已经检查了它们是否已经从组件继承,因此只有这些类型最终会出现在该列表中。

您正在寻找 IsSubClassOf 方法。注意:如果curType是同一类型的Component,这将报告false。在这种情况下,您可能需要添加Equals检查。

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

您可以使用IsSubClassOf

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

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

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

if (instance is Component)
{ }

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

object instance = Activator.CreateInstance(curType);

最新更新