如何为ASP.NET中的现有用户设置新配置文件属性的默认值?

如何为ASP.NET中的现有用户设置新配置文件属性的默认值?,asp.net,asp.net-profiles,Asp.net,Asp.net Profiles,我在profile类中添加了一个新的布尔属性 我似乎找不到一种方法,但是它的值在默认情况下是真实的 Profile.ShowDocumentsNotApplicable 未显式设置为true时返回false web.config内容: <!-- snip --> <profile inherits="Company.Product.CustomerProfile"> <providers> <clear /> <add

我在profile类中添加了一个新的布尔属性

我似乎找不到一种方法,但是它的值在默认情况下是真实的

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 -->

客户档案:

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();
        }
    }
}
公共类CustomerProfile:ProfileBase
{
私有bool\u showDocumentsNotApplicable=true;
公共bool showDocuments不合法
{
获取{return return(“ShowDocumentsNotApplicable”,_ShowDocumentsNotApplicable);}
set{set(“ShowDocumentsNotApplicable”,value,()=>\u ShowDocumentsNotApplicable=value);}
}
私有T返回(字符串propertyName,T defaultValue)
{
尝试
{
返回(T)基[propertyName];
}
捕获(设置属性NotFoundException)
{
返回默认值;
}
}
私有无效集(字符串propertyName、T setValue、System.Action defaultAction)
{
尝试
{
基本[propertyName]=设置值;
}
捕获(设置属性NotFoundException)
{
defaultAction();
}
}
}

对于布尔属性,您通常会发现它们可以用任意一种方式表示。我认为最好的做法是让他们以“虚假”的默认方式。因此,如果默认情况下希望
Profile.ShowDocumentsNotApplicable
为true,那么我将其称为
Profile.HideDocumentsNotApplicable
,默认值为false。这背后的原因是编译器将未初始化的布尔设置为false;让逻辑的默认值与编译器的默认值匹配是有意义的

如果反面不太合适(例如,您总是使用
!Profile.hiddedocumentsnotaplicable
,并且您发现这会降低可读性),则可以执行以下操作:

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

    //other stuff...
}