[英]Casting System.Type to a specific class
I'm getting the desired System.Type using reflection. 我正在使用反射获取所需的System.Type。 I need to check if it is a descendant of Component class.
我需要检查它是否是Component类的后代。 If it is I need to add this particular class to List.
如果是这样,我需要将此特定的类添加到列表。 What is the proper way to convert types?
转换类型的正确方法是什么?
foreach (Type curType in allTypes)
{
if (curType descends from Component)
componentsList.Add( (Component)curType );
}
You can use IsSubClassOf
: 您可以使用
IsSubClassOf
:
if (typeof(Component).Equals(curType) || curType.IsSubClassOf(typeof(Component)))
{ }
Nonetheless, the Type
is still a type , and not an instance , so if you think of adding instances to the list, you should check the instance, not the type. 尽管如此,
Type
仍然是type ,而不是instance ,因此,如果您考虑将实例添加到列表中,则应检查实例,而不是类型。
If you have an instance, you'd better use is
: 如果你有一个实例,你最好使用
is
:
if (instance is Component)
{ }
If you intend to create a new instance of a specific type, use Activator.CreateInstance
: 如果打算创建特定类型的新实例,请使用
Activator.CreateInstance
:
object instance = Activator.CreateInstance(curType);
You're looking for IsSubClassOf method. 您正在寻找IsSubClassOf方法。 Note: this will report false if the
curType
is of same type of Component
. 注意:如果
curType
与Component
类型相同,则将报告false。 You may need to add Equals
check in that case. 在这种情况下,您可能需要添加
Equals
检查。
if (curType.IsSubclassOf(typeof(Component)))
{
//Do stuff
}
Casting of a type is not possible, but as you say in the comments: 类型的转换是不可能的,但是正如您在注释中所说:
I need to create a list of all types
我需要创建所有类型的列表
So make your componentslist of type List<Type>
, and add the types to that list. 因此,使您的componentlist类型为
List<Type>
,然后将类型添加到该列表中。
You have done the check if they inherit from Component already, so only those types will end up in that list. 您已经检查了它们是否已经从Component继承,因此只有那些类型将最终出现在该列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.