c# - Maintainable Conversions -
i have class inherits base class; same, difference typeparam intellisense. want provide way convert existing parent class child class.
i doing way:
class { public int f1; public int f2; } class b<t> : { public static b<t> create(a a) { return new b<t> { f1 = a.f1; f2 = a.f2; }; } }
my concern not maintainable solution, , cause problems if new fields or properties added forgotten in create method. avoid reflection copy object.
is there better way accomplish this?
the typical way provide copy constructor within each class in hierarchy. example:
class { private int f1; private int f2; public a() { ... } public a(a original) { f1 = original.f1; f2 = original.f2; } } class b<t> : { public b(a original) : base(original) { } // possibly overload b(b<t> original) well? }
that way copying happens in class declares fields. best-placed know how handle fields; has access fields if they're private; when new field introduced, have make change in same class rather derived classes.
it's still ugly, , i'd avoid if possible - depends on context. (sometimes using composition instead of inheritance way forwards, that's not universally true.)
Comments
Post a Comment