简体   繁体   English

C# 派生 class 初始化

[英]C# derived class initialization

My C# code scenario:我的 C# 代码场景:

public class BaseClass 
{
       public int A;
       public float B;
       //a multitude of other fields
       public string Y;
};

public class DerivedClass:BaseClass {
       public string Z;
       public DerivedClass (BaseClass b) {
       //??
       }
}

I want to write this DerivedClass constructor without explicit memberwise copy.我想在没有显式成员复制的情况下编写这个 DerivedClass 构造函数。 In C++, a default BaseClass constructor would do it for me.在 C++ 中,默认的 BaseClass 构造函数会为我完成。 Thank you in advance.先感谢您。

You're asking if there's an easy way to create a copy constructor in C#.您问是否有一种简单的方法可以在 C# 中创建复制构造函数。

No, there is no way to do this without specifying the fields you want to copy in one of the constructor explicitly.不,如果不明确指定要在其中一个构造函数中复制的字段,就无法做到这一点。

see the docs for more info.有关更多信息,请参阅文档

I don't know an easy way to write fully functional copy constructor in c#.我不知道在 c# 中编写功能齐全的复制构造函数的简单方法。 So either you implement it in BaseClass manually or you can use reflection to automate it.因此,您可以手动在BaseClass中实现它,也可以使用反射来自动化它。

Last option would be to try to use Automapper which will have some limitations(but for provided code should work) in terms what it can handle - only public properties/fields will be mapped and implementation will look like this:最后一个选择是尝试使用Automapper ,它有一些限制(但对于提供的代码应该可以工作),就它可以处理的内容而言 - 只有公共属性/字段将被映射,实现将如下所示:

public class BaseClass
{
    private static readonly IMapper _mapper;
    static BaseClass()
    {
        var config = new MapperConfiguration(cfg => cfg.CreateMap<BaseClass, BaseClass>());
        _mapper = config.CreateMapper();
    }
    public int A;
    public float B;
    //a multitude of other fields
    public string Y;
    public BaseClass(){}
    public BaseClass(BaseClass b)
    {
        _mapper.Map<BaseClass, BaseClass>(b,this);
    }
};

public class DerivedClass : BaseClass
{
    public string Z;
    public DerivedClass(BaseClass b): base(b)
    {
    }
}

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

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