2010-06-16 83 views
0

我知道你可以使用这样的web.config中添加defaultValues:如何将默认值添加到自定义ASP.NET配置文件属性

<profile> 
    <properties> 
     <add name="AreCool" type="System.Boolean" defaultValue="False" /> 
    </properties> 
</profile> 

但我从类继承的个人资料:

<profile inherits="CustomProfile" defaultProvider="CustomProfileProvider" enabled="true"> 
    <providers> 
    <clear /> 
    <add name="CustomProfileProvider" type="CustomProfileProvider" /> 
    </providers> 
</profile> 

继承人的类:

Public Class CustomProfile 
    Inherits ProfileBase 

    Public Property AreCool() As Boolean 
     Get 
      Return Me.GetPropertyValue("AreCool") 
     End Get 
     Set(ByVal value As Boolean) 
      Me.SetPropertyValue("AreCool", value) 
     End Set 
    End Property 

End Class 

我不知道如何设置属性的默认值。它由于没有默认值而导致错误,它使用空字符串,它不能转换为布尔值。我尝试加入<DefaultSettingValue("False")> _,但这似乎没有什么区别。

我还使用自定义ProfileProvider(CustomProfileProvider)。

回答

0

只是一个想法,你可以做这样的事情或一些变化(指代替。长度,使用dbnull.value()或不过你需​​要检查它是否是一个实际的项目?

编辑代码处理空集参数

公共类CustomProfile 继承ProfileBase

Dim _outBool as boolean 
Public Property AreCool() As Boolean 
    Get 
     Return Me.GetPropertyValue("AreCool") 
    End Get 
    Set(ByVal value As Object) 
     ''if the value can be parsed to boolean, set AreCool to value, else default to false'' 
     If([Boolean].TryParse(value, outBool) Then 
      Me.SetPropertyValue("AreCool", value) 
     Else 
      Me.SetPropertyValue("AreCool", False) 
     End If 

    End Set 
End Property 

末级

+0

我认为错误来自Set,“”错误值为布尔参数 – 2010-06-16 21:27:20

+0

更新了Set部分。你也可以在这里进行逻辑检查,如果你需要对属性的设置进行手动覆盖。在这里,使用boolean.tryParse而不是字符串长度。 – Tommy 2010-06-16 23:02:04

+0

它甚至不会输入Set函数,因为它将值空参数 – 2010-06-17 13:11:09

0

的typic微软在整个.NET框架中都这样做的方式是使用get部分来检查值是否可以转换并返回默认值(如果不能)。例如:

Public Class CustomProfile 
    Inherits ProfileBase 

    Public Property AreCool() As Boolean 
     Get 
      Dim o as Object = Me.GetPropertyValue("AreCool") 
      If TypeOf o Is Boolean Then 
       Return CBool(o) 
      End If 
      Return False 'Return the default 
     End Get 
     Set(ByVal value As Boolean) 
      Me.SetPropertyValue("AreCool", value) 
     End Set 
    End Property 

End Class 
相关问题