2013-04-30 69 views
0

我爲我的個人檔案類添加了一個新的布爾屬性。如何爲ASP.NET中現有用戶的新配置文件屬性設置默認值?

我似乎無法找到一種方法,但默認情況下它的值爲true。

Profile.ShowDocumentsNotApplicable 

返回false時,沒有明確設置爲true ...

web.config文件內容:

<!-- snip --> 
<profile inherits="Company.Product.CustomerProfile"> 
    <providers> 
    <clear /> 
    <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" /> 
    </providers> 
</profile> 
<!-- snap --> 

CustomerProfile:

public class CustomerProfile: ProfileBase 
{ 
    private bool _showDocumentsNotApplicable = true; 

    public bool ShowDocumentsNotApplicable 
    { 
     get { return Return("ShowDocumentsNotApplicable", _showDocumentsNotApplicable); } 
     set { Set("ShowDocumentsNotApplicable", value,() => _showDocumentsNotApplicable = value); } 
    } 

    private T Return<T>(string propertyName, T defaultValue) 
    { 
     try 
     { 
      return (T)base[propertyName]; 
     } 
     catch (SettingsPropertyNotFoundException) 
     { 
      return defaultValue; 
     } 
    } 

    private void Set<T>(string propertyName, T setValue, System.Action defaultAction) 
    { 
     try 
     { 
      base[propertyName] = setValue; 
     } 
     catch (SettingsPropertyNotFoundException) 
     { 
      defaultAction(); 
     } 
    } 
} 

回答

1

布爾屬性,你會經常發現他們可以用任何方式表達。我認爲最好的做法是讓他們以任何方式使「默認」成爲「假」。因此,如果默認情況下,您希望Profile.ShowDocumentsNotApplicable爲真,那麼我會將其稱爲Profile.HideDocumentsNotApplicable,默認爲false。這背後的原因是編譯器將未初始化的bools設置爲false;讓邏輯的默認值與編譯器的默認值相匹配是有意義的。

如果反向不太適合(例如,你總是使用!Profile.HideDocumentsNotApplicable,你會發現這降低了可讀性),那麼你可以做到以下幾點:

public class CustomerProfile: ProfileBase 
{ 
    private bool _hideDocumentsNotApplicable; 
    public bool ShowDocumentsNotApplicable 
    { 
     get { return !_hideDocumentsNotApplicable); } 
     set { _hideDocumentsNotApplicable = !value); } 
    } 

    //other stuff... 
} 
相關問題