How can I instantiate a base class and then convert it to a derived class?

I was wondering how to do this, consider the following classes

public class Fruit { public string Name { get; set; } public Color Color { get; set; } } public class Apple : Fruit { public Apple() { } } 

How can I create a new fruit, but introduced to Apple, there is a way to create a bunch of fruits and make them apples with a name and a set of flowers. Do I need to manually copy manually?

Of course it fails

 Fruit a = new Fruit(); a.Name = "FirstApple"; a.Color = Color.Red; Apple wa = a as Apple; System.Diagnostics.Debug.Print("Apple name: " + wa.Name); 

I need to pass Fruit to AppleCTor and manually set the name and color (or 1-n properties). Is there a better design for this?

+4
source share
4 answers

Fruit not Apple in your model - if you want Apple , create an instance. . If you want to create Apple using Fruit as a starting point, create an Apple constructor that can accept Fruit .

It should be noted that object models in which intermediate classes in the inheritance hierarchy are real (not abstract) are often bad ideas. In some cases, such hierarchies may be appropriate - but I have found that in general they present a greater problem than they are worth. Think very hard about whether Fruit and Apple should be specific and realistic.

+5
source

By default, instance a is an instance of Fruit and will not convert to Apple . This is not an instance of Apple and never will be.

However, you can perform an explicit cast .

+6
source

It sounds like you're trying to create a way to create one of many possible objects derived from a common base class. This is usually done using the abstract Factory template. For more information and implementation examples, see: http://en.wikipedia.org/wiki/Abstract_factory_pattern

+4
source

If you create Fruit, it is not Apple. You cannot upgrade it, because it probably will not have all the attributes that it will need. If you want Apple, create Apple. You do not need to transmit anything.

I suspect the following will work:

 Fruit a = new Apple(); System.Diagnostics.Debug.Print("Apple name: " + a.Name); 

... but I'm not a Java programmer. This is basically what you would do in C ++. (Be sure to read the Abstract Factory Pattern link provided in another answer, especially if you need to instantiate many different subtypes of Fruit.)

+2
source

Source: https://habr.com/ru/post/1304918/


All Articles