我有一个人类简单的两个属性年龄和名称。然后,我有另一个类女派生自人类类,它有一个额外的属性FavCream。现在,我有这些类的两个不同的实例说H1和W1(派生类的女人)和I(基类人的)只是想覆盖与的W1所有派生属性相应的值从h1。如何重写派生类继承的属性值与基类实例
但是,我没有发现这个内置的。我不喜欢在Woman类中创建一个手动完成作业的公共方法。我认为,我可以使用反射功能创建一个实用功能,但要寻找经过验证的方法来处理这个问题。
这是不可能的吗?在这种情况下,我们不能有任何继承优势吗?或者这是不合逻辑的?
请耐心等待我。谢谢!
class Program
{
private static Woman _aWoman;
static void Main(string[] args)
{
var aHuman = new Human() { Age = 25, Name = "Ram" };
Program._aWoman = new Woman() { Age = 22, FavCream = "Ponds" , Name = "Sita"};
Console.WriteLine("Woman is " + Program._aWoman.ToString()); // prints Age = 22 Name = Sita FavCream = Ponds
Console.WriteLine("Human is " + aHuman.ToString()); // prints Age = 25 Name = Ram
**// Do something here so woman derived property has auto over written with property of human instance.**
Console.WriteLine("after overwriting, woman is " + _aWoman.ToString());
// The result I m looking for here is "Age = 25 Name = Ram FavCream = Ponds"
}
}
internal class Human
{
public int Age { get; set; }
public string Name { get; set; }
public override string ToString()
{
return "Age = " + this.Age + " Name = " + this.Name;
}
}
internal class Woman: Human
{
public string FavCream { get; set; }
public override string ToString()
{
return base.ToString() + " FavCream = " + this.FavCream;
}
}
UPDATE: 我关于创建方法结束,并且使用反射拷贝的基类的属性。此外,我试图用通用限制来增强这一点,但还没有成功。
感谢大家这样的快速回复。
// Trying to make it generic... but could not enforce contraint that T must be base class of 'this'
public void Overwrite<T>(T baseInstance) where T : Human
{
Type baseType = baseInstance.GetType();
Type derivedType = this.GetType();
PropertyInfo[] propInfos = null;
propInfos = baseType.GetProperties();
foreach (PropertyInfo eachProp in propInfos)
{
PropertyInfo baseProp = (baseType).GetProperty(eachProp.Name);
object baseVal = baseProp.GetValue(baseInstance, null);
eachProp.SetValue(this, baseVal, null);
}
}
什么,如果你有两个实例人类h1和h2?你想从哪里得到属性? –