从派生类复制一个基类的内容 [英] Copying the contents of a base class from a derived class

查看:108
本文介绍了从派生类复制一个基类的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有一个派生类的基类。我怎样才能让基类派生类的等于我有一个基类?将浅拷贝工作。



  Base类
{
私人字符串名称?;
公共字符串名称{;组; }
私人字符串的地址;
公共字符串地址{搞定;组; }
}

类派生:基本
{
私人串场;
公共字符串域{搞定;组; }
}

命名ConsoleApplication1
{
类节目
{
静态无效的主要(字串[] args)
{
基地b =新基地();
b.Address =Iliff;
b.Name =somename;

派生D =新派生的();
//我怎样才能让基类的ð等于b?

}
}
}


解决方案

如果我理解正确的话,这将工作:

 类派生:基本
{
//所有的代码,你有以上,再加上这样的:

公共派生(基本toCopy)
{
this.name = toCopy.name;
this.address = toCopy.address;
}
}

派生D =新派生的(B);


I currently have a derived class and a base class. How can I make the base class of the derived class equal to a base class that I have? Will a shallow copy work?

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 ?

        }
    }
}

解决方案

If I understand you correctly, this will work:

class Derived : Base
{
    // all the code you had above, plus this:

    public Derived(Base toCopy)
    {
        this.name = toCopy.name;
        this.address = toCopy.address;
    }
}

Derived d = new Derived(b);

这篇关于从派生类复制一个基类的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆