Casting back to derived class from base class using Reflections

与世无争的帅哥 提交于 2019-12-11 18:01:36

问题


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];


来源:https://stackoverflow.com/questions/9951709/casting-back-to-derived-class-from-base-class-using-reflections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!