简体   繁体   English

如何自动将派生类对象转换为新的基类对象?

[英]How to automatically convert derived class object to new base class object?

B is a class derived from A . B是从A派生的类。 I need to create a new object A from existing object B .我需要从现有对象B创建一个新对象A

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.我需要这个,因为在我的应用程序中,我使用了很多A实例,它们的重量比B (保存大量参考数据)轻得多,否则我会耗尽内存。

How do I convert B to A without manually copying all A 's fields' values in a custom method?如何A不手动复制自定义方法中所有A的字段值的情况下将B转换为A

Consider using composition (ie your B contains a private A as member data) instead of inheritance.考虑使用组合(即您的B包含一个私有A作为成员数据)而不是继承。 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.B添加一个方法以返回其A ,这样您就可以在B的其余部分被垃圾收集时保留它。

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 .请注意,在幕后,这仍然是B的相同实例,您只是将其视为A If you are looking to create a clone of B, then you should add a method to B:如果您想创建 B 的克隆,那么您应该向 B 添加一个方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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