2011-12-20 60 views
1

這是我寫的測試我的應用程序的app.config文件的值,我想知道這是一個好方法嗎?我直接在myProperty的getter/setter方法拋出一個ArgumentOutOfRangeException:它是一個很好的方式來測試ConfigurationElement屬性獲取/設置值

internal sealed class ProcessingMyPropertyElement : ConfigurationElement 
{ 
    [ConfigurationProperty("myproperty", IsRequired = true)] 
    public int MyProperty 
    { 
     get 
     { 
      if ((int)this["myproperty"] < 0 || (int)this["myproperty"] > 999) 
       throw new ArgumentOutOfRangeException("myproperty"); 

      return (int)this["myproperty"]; 
     } 
     set 
     { 
      if (value < 0 || value > 999) 
       throw new ArgumentOutOfRangeException("myproperty"); 

      this["recurEvery"] = value; 
     } 
    } 
} 
+0

聽起來很好。在getter中,我會添加一個int.TryParse以檢測配置文件中的非int值 – 2011-12-20 09:50:18

回答

2

當設定值是檢查的範圍,並拋出一個異常時,這是無效的一個好主意。

在得到它的時候,我不會拋出異常。這樣,有人可以通過手動編輯app.config來使應用程序崩潰。在你的getter中,我將限制值到特定的範圍並返回一個有效的結果。

if ((int)this["myproperty"] < 0) 
{ 
    return 0; 
} 

if ((int)this["myproperty"] > 999) 
{ 
    return 999; 
} 

return (int)this["myproperty"] 
相關問題