在.NET中初始化基类 [英] Initialize base class in .NET
问题描述
如果我需要使用现有对象初始化对象的基础,该怎么办?例如,在这种情况下:
How do I go about if I need to initialize an object's base with existing object? For example, in this scenario:
public class A
{
public string field1;
public string field2;
}
public class B : A
{
public string field3;
public void Assign(A source)
{
this.base = source; // <-- will not work, what can I do here?
}
}
Assign()方法显然可以逐字段为基类分配值,但是没有更好的解决方案吗?由于类B继承自A,因此必须有一种方法可以将A分配给B.base
Assign() method can, obviously assign values to the base class field-by-field, but isn't there a better solution? Since class B inherits from A, there must be a way to just assign A to the B.base
在C ++中,这是一件微不足道的事情,但是我似乎无法掌握如何在.NET中做到这一点
In C++ this would be a trivial thing to do, but I can't seem to grasp how to do this in .NET
推荐答案
不幸的是,base
是只读的.
好吧,也许不是那么不幸.基类和子类之间的关系是IS-A
而不是HAS-A
.通过允许子类更改基类的实例,可以允许子类更改其自身的引用,因为它是IS-A
基类.如果您确实需要此功能,那么我建议您更改继承模型以反映您真正想要做的事情.
Well perhaps not so unfortunate. The relationship between a base class and a child class is IS-A
not HAS-A
. By allowing a child class to change the instance of the base class you are allowing the child class to change its own reference since it IS-A
base class. If you truly need this functionality then I would suggest you change your inheritance model to reflect what you truly want to do.
类似这样的东西:
public class A
{
public string field1;
public string field2;
}
public class B
{
public string field3;
public A a;
public void Assign(A source)
{
this.a = source;
}
}
似乎更合适,并且含义和功能更清晰.
seems more appropriate and has clearer meaning and functionality.
这篇关于在.NET中初始化基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!