[VB.NET] 讀取app.config為指定變數型態

  • 1384
  • 0
  • 2022-02-14

網路上的實作都是C#版本,所以特將VB.NET版記錄下來。

以此文的C#版本為基礎,參考網路上C#與VB.NET對應語法得出以下程式:

<?xml version="1.0"?>
<configuration>
	<appSettings>
		<add key="BoolValue" value="true"/>
		<add key="IntValue" value="50"/>
	</appSettings>
</configuration>

 

Imports System.Configuration

Module ReadAppConfig

    Public Sub Main()

        Dim bln_Value As Boolean = GetAppSetting(Of Boolean)("BoolValue")
        Dim int_Value As Integer = GetAppSetting(Of Integer)("IntValue")

    End Sub

    Public Function GetAppSetting(Of T As IConvertible)(ByVal str_Key As String,
                                                        Optional ByVal obj_DefaultValue _
                                                        As T = CType(Nothing, T))

        Dim str_AppSettingName As String = ConfigurationManager.AppSettings(str_Key)
        Dim obj_ResultValue As T = obj_DefaultValue
        If str_AppSettingName IsNot String.Empty Then
            Dim obj_ValueType As T = CType(Nothing, T)
            obj_ResultValue = Convert.ChangeType(str_AppSettingName, obj_ValueType.GetTypeCode())
        End If
        Return obj_ResultValue

    End Function

End Module

另外還有複雜版,供參考: