AppSettingsReader.GetValue(String, Type) 方法

定义

AppSettings 属性中获取指定键的值,并返回指定类型的对象,该对象包含来自配置文件的值。

public:
 System::Object ^ GetValue(System::String ^ key, Type ^ type);
public object GetValue (string key, Type type);
member this.GetValue : string * Type -> obj
Public Function GetValue (key As String, type As Type) As Object

参数

key
String

要为其获取值的键。

type
Type

要返回的对象的类型。

返回

指定键的值。

例外

keynull

typenull

<appSettings> 配置节中不存在 key

- 或 -

key<appSettings> 配置节中的值不属于 type 类型。

示例

以下示例演示如何使用 GetValue 方法检索配置文件 的 节中 <appSettings> 每个键的值。

static void DisplayAppSettings()
{
    try
    {
        var reader = new AppSettingsReader();

        NameValueCollection appSettings = ConfigurationManager.AppSettings;

        for (int i = 0; i < appSettings.Count; i++)
        {
            string key = appSettings.GetKey(i);
            string value = (string)reader.GetValue(key, typeof(string));
            Console.WriteLine("Key : {0} Value: {1}", key, value);
        }
    }
    catch (ConfigurationErrorsException e)
    {
        Console.WriteLine("[DisplayAppSettings: {0}]", e.ToString());
    }
}
Private Shared Sub DisplayAppSettings()

    Try
        Dim reader As New AppSettingsReader()

        Dim appSettings As NameValueCollection = ConfigurationManager.AppSettings

        For i As Integer = 0 To appSettings.Count - 1
            Dim key As String = appSettings.GetKey(i)
            Dim value As String = reader.GetValue(key, GetType(String))
            Console.WriteLine("Key : {0} Value: {1}", key, value)
        Next i

    Catch e As ConfigurationErrorsException
        Console.WriteLine("[DisplayAppSettings: {0}]", e.ToString())
    End Try

End Sub

适用于

另请参阅