派生和基类,我可以明确设置基数吗?

Wat*_*son 16 c# reflection derived-class copy-constructor

public class SuperCar: Car
{
     public bool SuperWheels { get {return true; } }
}

public class Car 
{
     public bool HasSteeringWheel { get {return true;} }
}
Run Code Online (Sandbox Code Playgroud)

如何设置派生Supercar的基类?

例如,我想简单地设置SuperCars基类,如下所示:

public void SetCar( Car car )
{
SuperCar scar = new SuperCar();
car.Base = car; 
}
Run Code Online (Sandbox Code Playgroud)

基本上,如果我有Car对象,我不想手动遍历汽车的每个属性以设置SuperCar对象,我认为这是你可以做到的唯一方法,但如果你能以另一种方式做到这一点会好得多.

小智 11

我在子类中使用这样的东西,它对我来说很好:

using System.Reflection;
.
.
.
/// <summary> copy base class instance's property values to this object. </summary>
private void InitInhertedProperties (object baseClassInstance)
{
    foreach (PropertyInfo propertyInfo in baseClassInstance.GetType().GetProperties())
    {
        object value = propertyInfo.GetValue(baseClassInstance, null);
        if (null != value) propertyInfo.SetValue(this, value, null);
    }
}
Run Code Online (Sandbox Code Playgroud)


Wat*_*son 1

总的来说,有很多有用的评论。我认为 pst 给出了简短的答案,我认为这是正确的:

否。简短原因:没有单独的基础对象。(object)this == (object)base 始终为真。不过,有一些方法可以通过反射(和其他方式)执行克隆/复制。也许描述一下真正想要的东西

因此,他关于使用自动映射器工具的建议也非常有用,并且基本上就是我所寻找的。