C# inheritance. Derived class from Base class

后端 未结 4 2004
一生所求
一生所求 2020-12-15 06:28

I have a base class

public class A   
{
    public string s1;
    public string s2;
}

I also have a derived class :

public         


        
4条回答
  •  鱼传尺愫
    2020-12-15 06:30

    You can also use a JSON serializer for example. You add a static method to your child-class which could then be called like this:

    var porsche = Porsche.FromCar(basicCar);
    

    Here, "Porsche" is the child class and "Car" is the base class. The function would then look something like this:

    public class Porsche : Car
    {
        public static Porsche FromCar(Car basicCar)
        {
            // Create a JSON string that represents the base class and its current values.
            var serializedCar = JsonConvert.SerializeObject(basicCar);
    
            // Deserialize that base class string into the child class.
            return JsonConvert.DeserializeObject(serializedCar);
        }
    
        // Other properties and functions of the class...
    }
    

    The trick here is, that properties that are available in the child but not the base, will be created with their default value, so null usually, depending on the type of the property. The deserialization also goes by the name of the property, so all properties are copied over.

    I didn't test this code, but it should work, as I've done this once or twice before. Hope it helps someone.

提交回复
热议问题