2013-01-16 44 views
0

我有一個對象有一個業務規則列表,當對象被驗證時被檢查。避免「非常量字段不應該是可見的」代碼分析警告

在我創建類型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。

那麼有沒有更好的方法來解決這個問題?我應該將它們暴露爲下面的屬性嗎?

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

或者有沒有更好的方法來解決這個問題?

+4

也使用'readonly'。 – leppie

回答

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

感謝您的建議。我已經使業務規則屬性不可變,但靜態分析器不能告訴,所以它抱怨我可能只是可變的對象。如果對象不可變,我必須禁用警告。可惜它沒有檢測到。 –

+0

@RossDargan如果'BusinessRule'但屬性沒有標記爲'readonly' - 只要將另一個創建的規則重新分配給'NameRequiredRule',您仍然更改更改'NameRequiredRule'的一個實例 –

+0

我已經標記爲只讀,它被標記爲只讀當它發出上述警告時。確切的錯誤是「從'SyncFile.UploadedByRequiredRule'中刪除只讀標識或將字段更改爲不可變引用類型的字段。如果引用類型'BusinessRule'實際上是不可變的,請排除此消息」 –

相關問題