简体   繁体   中英

Casting System.Type to a specific class

I'm getting the desired System.Type using reflection. I need to check if it is a descendant of Component class. 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 :

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.

If you have an instance, you'd better use is :

if (instance is Component)
{ }

If you intend to create a new instance of a specific type, use Activator.CreateInstance :

object instance = Activator.CreateInstance(curType);

You're looking for IsSubClassOf method. Note: this will report false if the curType is of same type of Component . You may need to add Equals check in that case.

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.

You have done the check if they inherit from Component already, so only those types will end up in that list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM