[英]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.