Can I instance a class that inherits the values of an instance of a superclass?
I am using C#, but I think this is a pretty generic OO question. Suppose I have a class called Animal, and it has properties like LegCount, EyeCount, HasFur, EatsMeat, etc.
Let's say I have an instance a
of Animal. Suppose a
has LegCount set to 4 and EyeCount set to 2.
Now, I'd like to create an instance d
of type Dog, which inherits from Animal. I'd like to initialize d
with all the values of a
. I realize I could create a constructor or otherwise some other method that would take an Animal and spit out a new Dog with all the values copied in, but I was hoping there was some Object Oriented principle / trick that had me covered.
What I want to do, in plain English, is:
Create new Instance d
of Dog, with all starting values from a
. The key is "all", as opposed to specifying each property individually.
When you design a class that inherits from some other class, you don't need to list all the members it inherits. It just inherits all of them. So I am wondering if I can "inherit the values" 开发者_运维百科on actual instances.
The feature you want is called "prototype inheritance" or "prototype-oriented programming". C# does not support this feature, so you're out of luck there.
You might consider using a language that supports prototype inheritance if your architecture fundamentally needs this feature. JavaScript is the most commonly used prototype inheritance language.
Prototype inheritance can be quite tricky to get correct if you're not careful. If this subject interests you, see my article on some of the bizarre situations you can run into with prototype inheritance in JScript:
http://blogs.msdn.com/b/ericlippert/archive/2003/11/06/53352.aspx
You can't do what you're asking for with some C# language construct, you have to manually write mapping or delegating code. Or, take a look at AutoMapper
for that.
You could try a different approach with using the decorator pattern? An alternative to subclassing for extending functionality. Then all your values in the Animal class instance is preserved
http://www.dofactory.com/Patterns/PatternDecorator.aspx
public class Animal
{
public Animal(Animal otherAnimal)
{
if (otherAnimal == null)
throw new ArgumentNullException("otherAnimal");
foreach (System.Reflection.PropertyInfo property
in typeof(Animal).GetProperties())
{
property.SetValue(this, property.GetValue(otherAnimal, null), null);
}
}
}
and then just call this Animal constructor from your Dog(Animal otherAnimal) constructor
But still you should to think over one more time about design of your classes and make Animal an abstract class. Because what do you imagine as instance of class Animal..
精彩评论