简体   繁体   中英

How to automatically convert derived class object to new base class object?

B is a class derived from A . I need to create a new object A from existing object B .

I need this because in my application I use a lot of A instances which are much more light weigh than B (which holds a lot of reference data), otherwise I would run out of memory.

How do I convert B to A without manually copying all A 's fields' values in a custom method?

Consider using composition (ie your B contains a private A as member data) instead of inheritance. Add a method to B to return its A , so you can keep hold of it while the rest of the B is garbage collected.

Just cast it:

var a = (A)b;

or

var a = b as A;

A class that extends another can always be cast down to the more primitive version. Note that under the hood this is still the same instance of B , you are just treating it as A . If you are looking to create a clone of B, then you should add a method to B:

public class B : A  
{
    public A Clone()
    {
        var a = new A();
        a.SomeProperty = this.SomeProperty;
        ...etc...
        return a;
    }
}

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