我在配置文件类中添加了一个新的布尔属性。
我似乎无法找到一种方法,默认情况下它的值是真的。
Profile.ShowDocumentsNotApplicable
在未明确设置为true时返回false ...
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();
}
}
}
答案 0 :(得分:1)
使用布尔属性,您经常会发现它们可以以任何方式表达。我认为最好的做法是让它们以“假”为默认值。因此,如果默认情况下您希望Profile.ShowDocumentsNotApplicable
为真,那么我将其称为Profile.HideDocumentsNotApplicable
,默认值为false。这背后的原因是编译器将未初始化的bool设置为false;让逻辑的默认值与编译器的默认值相匹配是有意义的。
如果反向不太适合(例如,您总是使用!Profile.HideDocumentsNotApplicable
并且发现这会降低可读性),那么您可以执行以下操作:
public class CustomerProfile: ProfileBase
{
private bool _hideDocumentsNotApplicable;
public bool ShowDocumentsNotApplicable
{
get { return !_hideDocumentsNotApplicable); }
set { _hideDocumentsNotApplicable = !value); }
}
//other stuff...
}