繁体   English   中英

如何使用Activator.CreateInstance将类转换为基类型以设置值?

[英]How do I downcast a class to its base type to set values using Activator.CreateInstance?

给定

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

问题

发生CallBack时,基类的更改已消失! 看到的是在Activator.Creatinstance之后立即看到的相同的基类上下文。

是否无法向下转换对象并从该类型的另一个类实例为其分配值?

可能的解决方案

我可以将基类包含在父类中,而不是继承。

这个想法; 我认为应该可以,但没有。 但是,这确实有点反模式。 我只是重构代码以确保严格分离关注点,并在继承链中创建了一个新类。 那解决了问题。 在一个基类中,我只是发生了太多事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM