繁体   English   中英

如何在 class 基础中为初始化属性使用通用初始化程序?

[英]How can I use a common initializer for init properties in a base class?

考虑 C# 11 中的以下类:

class BaseClass
{
    public required string BaseProperty { get; init; }
}

class ChildClass : BaseClass
{
    public required string ChildProperty { get; init; }
}

初始化派生 class 的标准方法是:

var a = new ChildClass
{
    BaseProperty = "abc",
    ChildProperty = "def"
};

这很好用,但如果基类 class 有很多属性或有很多派生类,就会变得乏味。 有没有什么方法可以为基类 class 使用一个通用的集中式初始化程序,以便只需要为派生类初始化额外的属性? 类似的东西(发明的语法如下):

void Main()
{       
    var a = new ChildClass : BaseInitializer()
    {
        ChildProperty = "def"
    };
}

BaseClass BaseInitializer()
{
    return new BaseClass
    {
        BaseProperty = "abc"
    };
}

如果没有这个功能, requiredinit关键字似乎只对不涉及 inheritance 的基本场景有用。

我的问题有点类似于Can I set SetsRequiredMembers or another attribute for only an member in C# 11? ,除了这个问题是询问如何将广泛的属性仅应用于一个属性,而我想知道如何在同一实例上使用两个不同的初始值设定项。

我认为 go 的方法是使用构造函数:

var a = new ChildClass(
    BaseInitializer(), 
    childProperty: "xxx");


record BaseClass
{
    public required string BaseProperty { get; init; }
}

record ChildClass : BaseClass
{
    [SetsRequiredMembers]
    public ChildClass(BaseClass original, string childProperty) : base(original)
    {
        ChildProperty = childProperty;
    }

    public required string ChildProperty { get; init; }
}

请注意Required Members C# 11 feature specification 说:

在这个带有 init 子句的提案的版本中,我们谈到了能够有以下场景:

 public class Base { protected required int _field; protected Base() {} // Contract required that _field is set } public class Derived: Base { public Derived(): init(_field = 1) // Contract is fulfilled and _field is removed from the required members list { } }

但是,此时我们已经从提案中删除了 init 子句,因此我们需要决定是否以有限的方式允许这种情况。 我们的选择是:(...)

暂无
暂无

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

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