c# - 从派生类复制基类的内容

标签 c#

我目前有一个派生类和一个基类。如何使派生类的基类等于我拥有的基类?浅拷贝有用吗?

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/

相关文章:

c# - 在给定数字的列表中找到最接近的较小值和较大值的最佳方法是什么

javascript - 如何处理 asp.net Httphandler 中的错误?

c# - 使用 LINQ 确定该序列包含其他序列,顺序相同

c# - 找到完全覆盖矩形集所需的最少固定大小矩形的算法

c# - 查询字符串和文本大小写

c# - Audit.NET Entity Framework Core - 相关实体管理

c# - 使用 ElasticSearch Nest 索引动态对象 - StackOverflow Exception

c# - 接口(interface)中的 ICollection 与另一个接口(interface)作为类型

c# - 在多个用户控件之间共享属性

c# - Visual Studio 工具箱不包括来自同一解决方案的另一个项目的用户控件