避免"非常量字段不应该是可见的"代码分析警告

时间:2013-01-16 10:10:12

标签: c# code-analysis

我有一个对象,其中包含在验证对象时检查的业务规则列表。

在课程的顶部,我创建了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; }
    }

或者有更好的方法来解决这个问题吗?

1 个答案:

答案 0 :(得分:5)

您可以将静态字段声明更改为此

 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; }
}