如何使用Activator.CreateInstance将类向下转换为其基类型以设置值
本文关键字:基类 类型 设置 转换 Activator 何使用 CreateInstance | 更新日期: 2023-09-27 18:26:23
给定
//all types of T inherit class name of BaseClass...
public void Test<T>(Action<T> CallBack){
var obj = (T) Activator.CreateInstance<T>();
//Debugger shows obj of proper type and shows its proper baseclass
//now I want to change the base class and pass in a value to affect content
var bc = new BaseClass("Parameter1");
//downcast the original obj to type of baseclass
var bcObj = (BaseClass)obj;
//and assign the downcast object the new BaseClass
bcObj = bc;
//debugger shows bcObj IS the same as bc..
//but callback will not send the new bcObj content...
CallBack(obj);
}
问题
当回调发生时,基类的更改就消失了!所看到的是在Activator.Createnstance.之后看到的相同基类上下文
问题
是否不可能从该类型的另一个类实例向下转换对象并为其赋值?
可能的解决方案
我可以将基类包含在超类中,而不是继承。
想法;我想,应该工作,但没有。然而,这确实有点反模式。我只是重构了代码以确保严格分离关注点,并在继承链中创建了一个新的类。这解决了问题。我只是在其中一个基类中发生了太多的事情。