recreate instance in base class
I was wondering if it is possible to change the type of an instance of a derived class in it's base class to another derived class from the same base . following I will try to explain it in a code .
public class ValueTypeClass
{
private string _Note;
private String _Name;
private nodeClass refrenceNode ;
//...
}
public class refrenceDBClass : valuetypeclass
{
//...
}
public class refrenceFileClass : valuetypeclass
{
//...
}
now each time the refrenceNode is changed I want to change the type of the instance based on the refrenceNode properties
Edit 1 : Now I'm doing this by having another class which keeps the detail of refrencedbclass and refrencefileclass and everytime the refrencenode is changed I'm creating a new instance .
public class ValueTypeClass
{
private string _Note;
private String _Name;
private nodeClass refrenceNode ;
private detailClass detailInfo ;
//...
}
public c开发者_开发技巧lass detailClass
{
//...
}
public class refrenceDBClass : detailClass
{
//...
}
public class refrenceFileClass : detailClass
{
//...
}
In C#, an instance never changes its type.
I don't understand the problem you want to solve with this, but I assume that you should aggregate this type you want to change, and create a new instance if some value changes. Like the strategy pattern, for instance.
You can not change the type of a managed .NET object. If you were encapsulating the object (in a wrapper - for example refrenceNode
) you could swap the reference, but that is about it.
In some (limited) cases, you might be able to serialize/deserialize an encapsulated instance, changing the type in the process (only works for contract-based serializers, with compatible contracts; very unlikely). You certainly can't change the type of the current instance.
Re the edit; again, you can't change the type of how you expose the details, but with some casting you could make it work; vaguely, something like:
public class ValueTypeClass
{
private string _Note;
private String _Name;
private nodeClass refrenceNode;
public nodeClass ReferenceNode {
get {return refrenceNode;}
set {
if(refrenceNode == value) return; // nop
refrenceNode = value;
BuildDetailInfo();
}
}
private detailClass detailInfo;
public detailClass DetailInfo {get {return detailInfo;}}
private void BuildDetailInfo() {
// TODO: decide on the appropriate type (based on refrenceNode)
// and recreate detailInfo
}
}
It sounds like you should also be making use of polymorphism. If you are doing data-binding there are some other things you can do (with considerable effort) to make this more friendly, but it won't affect regular code.
精彩评论