Casting back to derived class from base class usin

2019-08-24 12:04发布

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?

2条回答
孤傲高冷的网名
2楼-- · 2019-08-24 12:38

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);
查看更多
Lonely孤独者°
3楼-- · 2019-08-24 12:49

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];
查看更多
登录 后发表回答