我有一个对象,其中包含在验证对象时检查的业务规则列表。
在课程的顶部,我创建了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; }
}
或者有更好的方法来解决这个问题吗?
答案 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; }
}