使用Reflections从基类投射回派生类 [英] Casting back to derived class from base class using Reflections

查看:85
本文介绍了使用Reflections从基类投射回派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想做的事情:

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

但是,我需要从DerivedClass到达要显示的一个属性,等等.BaseClass没有该属性,因此我无法实现.

因此我需要以某种方式将其强制转换回DerivedClass才能实现,但没有引用DerivedClass,所以我无法实现它的类型很简单,与具有引用的BaseClass不同,因此我可以使用它.

我该怎么做?

解决方案

在这种情况下,您基本上有两个选择:

  • 使用动态
  • 使用反射

使用动态

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

使用反射

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

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?

解决方案

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

这篇关于使用Reflections从基类投射回派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆