Casting back to derived class from base class usin

2019-08-24 12:54发布

问题:

Here what I am trying to do:

BaseClass base = (BaseClass)
AppDomain.CurrentDomain.CreateInstance("DerivedClassDLL","DerivedClass");

However, there is a property I need to reach from DerivedClass to display, etc. BaseClass doesn't have that property and I cannot make it happen.

So somehow I need to cast it back to DerivedClass to reach it BUT DerivedClass isn't referenced so I cannot reach it is type easily unlike BaseClass which has reference so I can use it.

How can I accomplish this?

回答1:

You basically have two options in this case:

  • use dynamic
  • use reflection

Using dynamic

BaseClass foo = (BaseClass) AppDomain.CurrentDomain
                                     .CreateInstance("DerivedClassDLL","DerivedClass");
dynamic derived = foo;
string someProperty = derived.SomeProperty;

Using reflection

string someProperty = (string)foo.GetType()
                                 .GetProperty("SomeProperty")
                                 .GetValue(foo, null);


回答2:

Since you have an instance of the derived class, this bit of reflection should do it:

var myPropertyInfo = typeof(instanceOfDerivedClass).GetProperty("DerivedClassProperty");
var myPropertyValue = myPropertyInfo.GetValue(instanceOfDerivedClass) as [property type];