开发者

Retrieve values from a config file into a class, in C#?

开发者 https://www.devze.com 2023-02-20 01:59 出处:网络
Using C#. how would one get values from a config file into a class? I guess you can pass a key and it will get the value based on that.

Using C#. how would one get values from a config file into a class? I guess you can pass a key and it will get the value based on that.

I know you can use

string value = ConfigurationManager.AppSettings["test"];

But I thought there might be a better way, maybe using it in a class?

Is this OK?

public static string GetKey(string value)
{
   get 
   {
     开发者_JAVA百科 return ConfigurationSettingAppSetting[value];
   }
}

and to use it I use

GetKey("test");

Is this good or good pratice using it as a static?

thanks


I prefer not to use strings to get values out of the configuration. Instead I create

public static class Config
{
    public static string Test
    {
        get { return ConfigurationManager.AppSettings["Test"]; }
    }
}

also allowing for strong typing

public static class Config
{
    public static int ApplicationId
    {
        get { return int.Parse(ConfigurationManager.AppSettings["ApplicationId"]); }
    }
}

This creates a simple abstraction without going all out and creating configuration sections.

0

精彩评论

暂无评论...
验证码 换一张
取 消