Please see the code:
class X
{
public string x;
}
class Y : X
{
public string y;
}
class A
{
string a;
public virtual X createX<T>()
where T : X, new()
{
return new T() { x = a };
}
}
class B : A
{
string b;
public override X createX<T>()
{
var x = base.createX<T>();
if (x is Y)
((Y)x).y = b; // Yak.
return y;
}
}
...
var c = new B();
var z = c.createX<Y>(); // Yak. I prefer to not needing to know the type Y
I dislike this code, trying to come up with the better way to refactor it. The general idea is quite simple, each class of the hierarchy has factory method to produce an instance of the counterpart class of mirror hierarchy. I get an instance of the root class or derivative class and need to return the instance of counterpart class or its derivative (as root counterpart class). Any ideas or design pattern I can implement instead?
Aucun commentaire:
Enregistrer un commentaire