我目前有一个派生类和一个基类。如何使派生类的基类等于我拥有的基类?浅拷贝有用吗?
class Base
{
private string name;
public string Name { get; set; }
private string address;
public string Address { get; set; }
}
class Derived:Base
{
private string field;
public String field { get; set; }
}
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Base b = new Base();
b.Address = "Iliff";
b.Name = "somename";
Derived d = new Derived();
//How can I make the base class of d equal to b ?
}
}
}
最佳答案
为基类创建一个复制构造函数,这样做时您还需要创建一个无参数的构造函数,并且通过添加复制构造函数,编译器将不再生成默认构造函数。然后在派生类中调用基类的拷贝构造函数。
public class Base
{
public int Name { get; set; }
public string Address { get; set; }
public Base()
{ }
public Base(Base toCopy)
{
this.Name = toCopy.Name;
this.Address = toCopy.Address;
}
}
public class Derived : Base
{
public String Field { get; set; }
public Derived(Base toCopy)
: base (toCopy)
{ }
// if desired you'll need a parameterless constructor here too
// so you can instantiate Derived w/o needing an instance of Base
public Derived()
{ }
}
关于c# - 从派生类复制基类的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14613919/