【发布时间】: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<T>()函数一个泛型类型约束:public void Test<T>(Action<T> CallBack) where T: BaseClass... 并且可能还有一个构造函数约束 @987654329 @
标签: c# callback polymorphism downcast activator