【问题标题】:default value as null for a bool type in a profile provider配置文件提供程序中布尔类型的默认值为 null
【发布时间】:2011-03-23 16:06:20
【问题描述】:

我在我的 webconfig 中定义了一个自定义配置文件。我已经定义了这个属性

<add name="sex" type="bool" serializeAs="String" defaultValue="[null]"/>

因为数据库中有空值。我在这段代码中得到一个空引用异常:

    ProfileCommon p = GetProfile();
            txtFirstName.Text = p.first_name;
            txtLastName.Text = p.last_name;
            txtInitial.Text = p.initial;
            txtEmail.Text = p.email;

//这会导致空引用异常 布尔? blnTest = p.sex;

这是在 webconfig 中设置默认空值的正确方法吗?

【问题讨论】:

  • 也许您希望bool? 使null 成为有效值?
  • 试过了。布尔?不被识别。一旦配置文件被初始化,它将抛出异常。
  • 重点是——你需要一个合适的数据类型,bool 不需要,因为它只能容纳true/false,你需要更多的状态。

标签: c# profile boolean asp.net-profiles


【解决方案1】:

这里的问题是配置文件属性的默认类型是 bool,它不是可以为空的类型。它始终默认为 false。

您总是可以创建一个自定义类来封装 Sex / Gender 并使用它而不是 bool。这样,当没有设置值时,该类将尝试实例化并根据需要恢复为 null。

对网络配置的更改:

 <profile defaultProvider="MyProfileProvider" inherits="FTS.Membership.Profile.MyProfileProvider,FTS.Membership">
      <providers>
        <clear/>
        <add name="MyProfileProvider" connectionStringName="LocalSqlServer" applicationName="/" type="FTS.Membership.Profile.MyProfileProvider,FTS.Membership"/>
      </providers>
      <properties>
        <add name="first_name" type="string" serializeAs="String" defaultValue=""/>
        <add name="last_name" type="string" serializeAs="String" defaultValue=""/>
        <add name="initial" type="string" serializeAs="String" defaultValue=""/>
        <add name="email" type="string" serializeAs="String"/>
        <add name="active" type="bool" serializeAs="String" defaultValue="false"/>
        <add name="creation_date" type="datetime" serializeAs="String"/>
        <add name="update_date" type="datetime" serializeAs="String"/>
        <add name="last_activity_date" type="datetime" serializeAs="String"/>
        <!--<add name="sex" type="bool" serializeAs="String" defaultValue="false"/>-->

      </properties>
    </profile>

和班级:

using System;
using System.Web.Profile;
using System.Collections.Generic;

namespace FTS.Membership.Profile
{
    public class MyProfileProvider : ProfileBase
    {
        public bool? sex
        {
            get {
                if (base["sex"] == null)
                {
                    return null;
                }
                return (bool)base["sex"];
            }
            set { base["sex"] = value; }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2020-10-07
    • 1970-01-01
    • 2011-03-19
    • 2014-03-03
    • 1970-01-01
    相关资源
    最近更新 更多