如何用基类初始化继承的类? [英] How to initialize inherited class with base class?
本文介绍了如何用基类初始化继承的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个此类的实例:
public class MyClass
{
public string Username { get; set; }
public string Password { get; set; }
public string GetJson()
{
return JsonConvert.SerializeObject(this);
}
}
但是在某些情况下,我需要序列化json中的更多属性.我以为我应该再做一个这样的继承类:
but in some cases I need more properties in serialized json. I thought I should make a second inherited class like this:
public class MyInheritedClass : MyClass
{
public string Email { get; set; }
}
如果我没有以错误的方式解决问题,如何使用第一个类的实例初始化第二个类的新实例,并从GetJson()
中获取一个包含所有三个属性的json字符串?
If I'm not solving the problem in the wrong way, how can I initialize a new instance of my second class with an instance of the first one and have a json string from GetJson()
that contains all the three properties?
推荐答案
您可以在派生类中创建构造函数并映射对象,
You can create a constructor in your derived class and map the objects,
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();
更新的构造函数:
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);
}
});
}
这篇关于如何用基类初始化继承的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文