我有一个 Human 类,只有两个属性 Age 和 Name 。然后,我有另一个派生自 Human 类的女性,它还有一个额外的属性 FavCream 。现在,我有这两个类的两个不同实例说 h1 (基类人类)和 w1 (派生类女人< / strong>)我只是想用 h1 中的相应值覆盖 w1 的所有派生属性。
但是,我没有找到这个内置的。我不喜欢在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;
}
}
更新 我最后创建了一个方法并使用反射复制了基类属性。此外,我尝试使用通用限制来增强此功能但尚未成功。
感谢大家的快速回复。
// 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);
}
}
答案 0 :(得分:2)
是的,你可以使用反射来做到这一点 获取人类
上的所有属性// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = typeof(Human).GetProperties(BindingFlags.Public |
BindingFlags.Static);
您可以使用PropertyInfo GetValue()和SetValue()方法从Human获取并将其设置为Woman。 查看MSDN:SetValue:http://msdn.microsoft.com/en-us/library/axt1ctd9.aspx GetValue:http://msdn.microsoft.com/en-us/library/b05d59ty.aspx
我建议您重载隐式或显式运算符,而不是在运行时分配值,而只是从人到女人进行转换。
Woman newWoman = (Woman)H1;
所有将Human转换为Woman的逻辑都将被转储到重载方法中。
答案 1 :(得分:0)
您创建的Human类实例与Woman类实例完全分开。 你很难看到你想要达到的目标,也许是这个?
w1.Age = h1.Age;
w1.Name = h1.Name;
答案 2 :(得分:0)
你所要求的是不合逻辑的。即使你有两个女性实例,w1和w2,也没有内置机制可以将所有属性从w1复制到w2。
您需要使用反射来实现它,但这是一个非常简单的操作。
答案 3 :(得分:0)
除了其他答案,你可以简单地在Human
类中编写一些函数来复制你感兴趣的属性:
class Human
{
...
public void CopyFrom(Human h)
{
this.Age = g.Age;
this.Name = g.Name;
}
}
其他解决方案可以使用automapper