如何用基类初始化继承的类?

Ble*_*ter 2 c# inheritance

我有这个类的一个实例:

public class MyClass
{
    public string Username { get; set; }
    public string Password { get; set; }

    public string GetJson()
    {
        return JsonConvert.SerializeObject(this);
    }
}
Run Code Online (Sandbox Code Playgroud)

但在某些情况下,我需要序列化json中的更多属性.我以为我应该像这样创建第二个继承的类:

public class MyInheritedClass : MyClass
{
    public string Email { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

如果我没有以错误的方式解决问题,我如何使用第一个类的实例初始化我的第二个类的新实例并且从中GetJson()包含所有三个属性的json字符串?

小智 7

您可以在派生类中创建构造函数并映射对象,

public class MyInheritedClass : MyClass
{
    MyInheritedClass (MyClass baseObject)
    {
        this.UserName = baseObject.UserName; // Do it similarly for rest of the properties
    }
    public string Email { get; set; }
}

MyInheritedClass inheritedClassObject = new MyInheritedClass(myClassObject);
inheritedClassObject.GetJson();
Run Code Online (Sandbox Code Playgroud)

更新的构造函数:

        MyInheritedClass (MyClass baseObject)
         {      
           //Get the list of properties available in base class
            var properties = baseObject.GetProperties();

            properties.ToList().ForEach(property =>
            {
              //Check whether that property is present in derived class
                var isPresent = this.GetType().GetProperty(property);
                if (isPresent != null && property.CanWrite)
                {
                    //If present get the value and map it
                    var value = baseObject.GetType().GetProperty(property).GetValue(baseObject, null);
                    this.GetType().GetProperty(property).SetValue(this, value, null);
                }
            });
         }
Run Code Online (Sandbox Code Playgroud)