-
Notifications
You must be signed in to change notification settings - Fork 3
Inheritance
Oliver Ehrenmüller edited this page Apr 12, 2019
·
5 revisions
Use DeepCopyExtension to create copies of instances within class hierarchy.
[DeepCopyExtension]
public static BaseClass DeepCopy(this BaseClass baseClass) => baseClass;
public class BaseClass { ... }
public class DerivedClass : BaseClass { ... }
public class OtherDerivedClass : BaseClass { ... }public static BaseClass DeepCopy(this BaseClass baseClass) {
if (baseClass == null)
return (BaseClass) null;
if (baseClass is DerivedClass derivedClass)
return (BaseClass) new DerivedClass(derivedClass);
if (baseClass is OtherDerivedClass otherDerivedClass)
return (BaseClass) new OtherDerivedClass(otherDerivedClass);
return new BaseClass(baseClass);
}[DeepCopyExtension]
public static AbstractBaseClass DeepCopy(this AbstractBaseClass baseClass) => baseClass;
public class AbstractBaseClass { ... }
public class DerivedClass : AbstractBaseClass { ... }
public class OtherDerivedClass : AbstractBaseClass { ... }public static AbstractBaseClass DeepCopy(this AbstractBaseClass baseClass) {
if (baseClass == null)
return (AbstractBaseClass) null;
if (baseClass is DerivedClass derivedClass)
return (AbstractBaseClass) new DerivedClass(derivedClass);
if (baseClass is OtherDerivedClass otherDerivedClass)
return (AbstractBaseClass) new OtherDerivedClass(otherDerivedClass);
throw new InvalidOperationException();
}