简体   繁体   中英

How to copy an instance of base class to derived class base using c#.net

I am encounter with a situation where I need to copy the members of base class to derived class. I have an Instance of Base class which are returning by some other service, the same class we have used as a base class for further classes.

When we crates an object of derived class I want to assign the already created instance of base class to derived class, I know we can not assign the base class object to derived class but I am still searching any other solution. Any one has any Idea?

Example :

public class VBase 
{
   public string Type {get;set;}
   public string Colour {get;set;}
}

public class Car : VBase 
{
   public string Name {get;set;}
   public int Year {get;set;}
}

// This class instance I am getting from some other source

VBase mBase= new VBase();  
mBase.Type = "SUV";
mBase.Colour = "Black";

//-------------------------------------------------------

Car myCar= new Car();
myCar.Name = "AUDI";
mBase.Year = "2016";

//here I want to copy the instance of base class to derived class some thing like this or any other possible way.

myCar.base=mBase;

It is not possible in naïve way.

I'd like to recommend to define constructor or static method. I personally do not recommend to use additional libraries like AutoMapper for this job as they could require some conversion and make code cumbersome.

public class Car : VBase 
{
    // Method 1: define constructor.
    public class Car(VBase v) {
        this.Type = v.Type;
        this.Colour = v.Colour;
    }

    // Method 2: static method.
    public static Car FromVBase(VBase v){
        return new Car()
        {
            this.Type = v.Type;
            this.Colour = v.Colour;        
        };
    }

    public string Name {get;set;}
    public int Year {get;set;}
}

Without using reflection, if your classes are lightweight, and wont change overtime, then you could create a public property of Base in Car :

public class Car : VBase
{
    public string Name
    {
        get;
        set;
    }

    public int Year
    {
        get;
        set;
    }

    public VBase Base
    {
        set
        {
            base.Type = value.Type;
            base.Colour = value.Colour;
        }
    }
}

You can then easily pass through your base class like so:

myCar.Base = mBase;

I have created a dotnetfiddle here:

dotnetfiddle for this question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM