2

オブジェクトが検証されるときにチェックされるビジネスルールのリストを持つオブジェクトがあります。

クラスの先頭に、以下に示すようにBusinessRuleタイプの静的フィールドを作成します。-

public class SyncFile : Waterstons.Patterns.Entities.BaseEntity<Guid>
{        
    public static BusinessRule NameRequiredRule = new BusinessRule("Name", "The audit file must have a name");
    ....


    protected override void Validate()
    {
        if (Id == default(Guid))
        {
            AddBrokenRule(IdRequiredRule);
        }
        ....

これは、constでない限り、パブリックフィールドを持つべきではないと不平を言うコード分析につながります。それらをconstとして定義できるかどうかはわかりませんが、使用方法に基づいています。

それで、これにアプローチするより良い方法はありますか?代わりに、以下のようにプロパティとして公開する必要がありますか?

    public static BusinessRule _nameRequiredRule = new BusinessRule("Name", "The audit file must have a name");
    public static BusinessRule Test
    {
        get { return _nameRequiredRule; }
    }

それとも、これにアプローチするためのより良い方法はありますか?

4

1 に答える 1

9

静的フィールド宣言をこれに変更できます

 public static readonly BusinessRule NameRequiredRule = new BusinessRule("Name", "The audit file must have a name");

したがって、実行中にパブリックフィールドが変更されないようにするためです。BusinessRuleまた、クラスを不変にして、参照を変更できないようにするだけでなく、NameRequiredRule実行時にインスタンスの内容を変更できないようにすることにも注意してください。

不変性を強制できない場合は、NameRequiredRule静的フィールドをプライベートとして宣言し、静的プロパティを作成することを検討してください。

private static BusinessRule _nameRequiredRule = new BusinessRule("Name", "The audit file must have a name");
public static BusinessRule NameRequiredRule
{
    get { return _nameRequiredRule; }
}
于 2013-01-16T10:13:41.330 に答える