Given
//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);
}
Problem
When the CallBack happens the change of the base class is gone! What is seen is the same base class context seen right after Activator.Creatinstance.
Question
Is it not possible to downcast an object and assign values to it from another class instance of that type?
Possible Solution
I could contain the baseclass in the super class instead of inheriting.
The idea; I thought, should have worked but did not. However, it's a bit of an anti-pattern indeed. I simply refactored the code to ensure strict separation of concerns and created a new class in the inheritance chain. That solved the problem. I simply had too much stuff going on in one of the base classes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.