首页 > 解决方案 > 是否有此 C# 属性声明的简短版本?

问题描述

由于构造函数的参数发生变化,我正在重构一些代码。我正在寻找声明此类属性的最清晰和简约的方式。

在此示例中,它Button已将构造函数从以前的带参数更改为不带参数。

最初的属性如下所示:

public Button Person
{
    get
    {
        if (AppPlatform == Platform.XYZ) return new Button(x => x.Id("imagePerson"));
        else return new Button(x => x.Id("c_person"));
    }
}

更改 Button 类构造函数后,我想出了这种声明属性的方式,但我发现它看起来太“大”或笨拙。

public Button Person
{
    get
    {
        if (AppPlatform == Platform.XYZ)
            controlIdQuery = x => x.Id("imagePerson");
        else
            controlIdQuery = x => x.Id("c_person");

        return this;
    }
}

此外,我会通过组合将属性添加到各种类中,如下所示:

public Button Person => new Buttons().Person;

所以我什至不确定该属性是否应该返回this。它可以像自己一样返回return Person吗?

当我需要将 Button 嵌入到无法controlIdQuery通过继承访问的类中时,笨拙变得更加糟糕:

public Button Down
{
    get
    {
        Button b = new Button { controlIdQuery = x => x.Id("imagePerson") };
        return b;
    }
}

TL;DR:这种类型的属性声明有简写版本吗?

标签: c#

解决方案


推荐阅读