【问题标题】:How do I downcast a class to its base type to set values using Activator.CreateInstance?如何将类向下转换为其基类型以使用 Activator.CreateInstance 设置值?
【发布时间】:2015-12-10 00:39:04
【问题描述】:

给定

//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.Creatinstance 之后看到的相同的基类上下文。

问题

是否不能向下转换一个对象并从该类型的另一个类实例为其赋值?

可能的解决方案

我可以在超类中包含基类而不是继承。

【问题讨论】:

  • 您从未在 obj 或 bcObj 上设置任何值,那么您为什么会期望任何更改?
  • 我不明白。所有bc 代码的意义何在?你也可以删除Activator.CreateInstance之后的所有内容,直到Callback(obj)之前的那一行
  • 注意T型都继承BaseClass,我正在尝试将新的BaseClass注入到父类中。
  • @TheSharpNinja 我确实将整个 bcObj 更改为 bc 的实例。
  • 如果 T 的所有类型都继承自 BaseClass,您可能希望给 Test&lt;T&gt;() 函数一个泛型类型约束:public void Test&lt;T&gt;(Action&lt;T&gt; CallBack) where T: BaseClass... 并且可能还有一个构造函数约束 @987654329 @

标签: c# callback polymorphism downcast activator


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 2015-10-06
    • 2019-09-16
    • 1970-01-01
    相关资源
    最近更新 更多