2010-06-16 85 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 
相關問題