2015-02-06 10 views
1

我有以下情形填充基继承的类作为一个对象,而不是每一个属性

方案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; 
    } 
} 

有一种方法来传递基类继承类“t”作为一个整体对象,而不是必须从基类的属性分配每个属性?

回答

1

有没有办法将基类继承的类“t”作为整个对象传递,而不必从基类的属性中指定每个属性?

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

您将需要逐个字段复制源类中的值。无论你是在这个构造函数中还是在一个基础构造函数中(如果你有多个你想要添加这个功能的子类,这会很有帮助),你是否明确地使用或者使用反射是由你决定的。

0

你可以在基类中创建copy constructor,并使用它像这样:

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

如果你不想处理基本副本构造函数中,你可以使用ReflectionExpression Trees以使自动化它

相关问题