将继承的基础 class 填充为一个对象而不是链接每个属性

Fill base inherited class as one object rather than linking each attribute

我有以下场景

场景 1:

public class TT : t
{
    public int x { get; set; }
    public TT(t name, int name2)
    {
        this.att1 = name.att1;
        this.att2 = name.att2;
        this.att3 = name.att3;
        x = name2;
    }
}

场景 2:

public class TT : t
{
    public int x { get; set; }
    public TT(t name, int name2)
    {
        this = name;
        x = name2;
    }
}

有没有办法将继承的基 class "t" 作为整个对象传递,而不必从基 class 中分配每个 属性特性?

您可以在基础 class 中创建 copy constructor 并像这样使用它:

public class TT : t
{
    public int x { get; set; }
    public TT(t name, x name2):base(name)
    {
        x = name2;
    }
}

如果您不想手动处理基本复制构造函数,您可以使用 Reflection and Expression Trees 使其自动化

Is there a way to pass the base inherited class "t" as an entire object, rather than having to assign each property from the base class's properties?

没有。您不能在 class(或任何其他方法)的构造函数中重新分配 this。另外,请记住 name 将是对象的 引用 ,而不是对象本身,因此即使您 可以 重新分配 this,你会指向同一个对象,而不是复制它的值。

您需要逐字段复制源 class 中的值。无论您是在此构造函数中还是在基础构造函数中执行此操作(如果您有多个子 class 想要添加此功能,这将很有帮助),以及您是显式执行还是使用反射给你。