简体   繁体   中英

Casting Error from Derived Class to Base Class

Getting casting error when trying to cast Derived1 and Derived2 to a TemplateControl type object so that I can add them to a list of TemplateClass objects. Using typeof(TemplateClass).IsAssignableFrom(t) does not match the type, even though it shows the basetype of t as TemplateClass.

class abstract TemplateClass : UserControl {}
class Derived1 : TemplateClass {}
class Derived2 : TemplateClass {}

 Type[] types = plugin.GetTypes(); //returning types for Derived1 and Derived2 correctly

 foreach (Type t in types)
 {
   if (typeof(UserControl).IsAssignableFrom(t)) 
   {
     var control = (TemplateClass)Activator.CreateInstance(t); // casting error here
     controls.Add(control);
   }
 }

EDIT:

The information i did not include above is that the object plugin is an Assemblly loaded from a dll. The dll is ModelControls. So TemplateClass is really ModelControls.TemplateClass and Derived1 and Derived2 are preceded with the same namespace. When i use Model.TemplateClass in the typeof().IsAssignable(t) it does not find any matching types, even though creating a new Type Array like the one below works fine.

 Type[] types = { typeof(ModelControls.Derived1), typeof(ModelControls.Derived2) };

You are failing since you are checking typeof(UserControl) and automatically casting to TemplateClass .

What happens if t is a UserControl ? You will get an invalid cast exception.

Here's a working example checking typeof(TemplateClass) :

    Type[] types = { typeof(Derived1), typeof(Derived2) };

    foreach (Type t in types)
    {
        if (typeof(TemplateClass).IsAssignableFrom(t)) // not typeof(UserControl)
        {
           var templateClass = (TemplateClass)Activator.CreateInstance(t);
        }
    }

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