在 C# 中使用 AppConfig 文件中的值

发布于 2024-11-14 05:47:24 字数 369 浏览 5 评论 0原文

selenium = new DefaultSelenium(
    ConfigurationManager.AppSettings["TestMachine"].ToString(),
    4444,       
    ConfigurationManager.AppSettings["Browser"].ToString(),        
    ConfigurationManager.AppSettings["URL"].ToString()
);

有没有一种有效的方法来做到这一点,而不是重复:

ConfigurationManager.AppSettings[""].ToString()
selenium = new DefaultSelenium(
    ConfigurationManager.AppSettings["TestMachine"].ToString(),
    4444,       
    ConfigurationManager.AppSettings["Browser"].ToString(),        
    ConfigurationManager.AppSettings["URL"].ToString()
);

Is there an efficient way to do this, instead of repeating:

ConfigurationManager.AppSettings[""].ToString()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

魂归处 2024-11-21 05:47:24

我认为更好的想法是为所有涉及配置的内容编写一个包装类,尤其是在编写测​​试时。一个简单的例子可能是:

public interface IConfigurationService
{
    string GetValue(string key);
}

这种方法将允许您在需要时模拟您的配置并降低复杂性

因此您可以继续:

public void SelTest(IConfigurationService config)
{
    var selenium = new DefaultSelenium(config.GetValue("TestMachine"),
        4444, config.GetValue("Browser"), config.GetValue("URL"));
}

或者您可以从列表继承您的配置并将输入减少为:

config["Browser"]

I think a better idea is to write a wrapper class to everything that deals with configuration, especially if you write tests. A simple example might be:

public interface IConfigurationService
{
    string GetValue(string key);
}

This approach will allow you to mock your configuration when you need it and reduce complexity

So you could proceed with:

public void SelTest(IConfigurationService config)
{
    var selenium = new DefaultSelenium(config.GetValue("TestMachine"),
        4444, config.GetValue("Browser"), config.GetValue("URL"));
}

or you could inherit your configuration from a List and reduce the typing to:

config["Browser"]
心房的律动 2024-11-21 05:47:24

是的,你可以这样做

ConfigurationManager.AppSettings[""]

,因为它已经是一个字符串。

如果您在多个位置使用 ConfigurationManager.AppSettings["Something"],则应该创建一个静态 Config 类,它通过静态属性读取您的 AppSettings。

Yes, you can do

ConfigurationManager.AppSettings[""]

As it is already a string.

If you're using ConfigurationManager.AppSettings["Something"] at multiple places, you should create a static Config class, that reads your AppSettings via static properties.

泛滥成性 2024-11-21 05:47:24

您可以转到项目的属性并添加设置,然后使用以下命令读取它:
属性.设置.默认.属性

You can go to the properties of the project and add Settings, then read it with:
Properties.Settings.Default.Property

忆沫 2024-11-21 05:47:24

我总是为每个应用程序创建一个配置类,它包装对 app/web.config 文件的访问并将配置条目公开为属性。例如,这样的:

public static class MyConfig
{
    /// documentation of config entry
    public static string Browser
    {
      get { return Read("Browser", "some default value"); }
    }

    /// documentation of config entry
    public static int Port
    {
      get { return int.Parse(Read("Browser", "80")); }
    }

    public static string Read(string entry, string defaultValue)
    {
        var entry = ConfigurationManager.AppSettings[entry];
        return string.IsNullOrEmpty(entry) ? defaultValue : entry;
    }
}

这有几个优点:

  • 我可以定义默认值(例如,如果配置条目是可选/缺失)
  • 我可以以正确的类型(int,bool)公开数字/布尔配置条目
  • 我可以记录所有配置条目一个中心的地方

I always create a config class per application which wraps access to the app/web.config file and exposes the config entries as properties. E.g. something like this:

public static class MyConfig
{
    /// documentation of config entry
    public static string Browser
    {
      get { return Read("Browser", "some default value"); }
    }

    /// documentation of config entry
    public static int Port
    {
      get { return int.Parse(Read("Browser", "80")); }
    }

    public static string Read(string entry, string defaultValue)
    {
        var entry = ConfigurationManager.AppSettings[entry];
        return string.IsNullOrEmpty(entry) ? defaultValue : entry;
    }
}

This has several advantages:

  • I can define default values (e.g. if a config entry is optional/missing)
  • I can expose numerical/boolean config entries in the correct type (int, bool)
  • I can document all config entries in a central place
甜心小果奶 2024-11-21 05:47:24

如果您想要强类型引用,可以继承 ConfigurationSection / ConfigurationElementCollectionConfigurationElement

您可以使用 [ConfigurationProperty("key", IsRequired = true, DefaultValue = "*^%)(@")] 和验证器 (如 ) 为 ConfigurationElement 指定默认值>[StringValidator(MinLength = 3)] 等。

If you want have strong type reference, you can inherit from ConfigurationSection / ConfigurationElementCollection and ConfigurationElement.

You can specify default value to ConfigurationElement with [ConfigurationProperty("key", IsRequired = true, DefaultValue = "*^%)(@")] and validator like [StringValidator(MinLength = 3)] etc.

无声静候 2024-11-21 05:47:24

编写一个辅助函数来获取参数。为了良好的编码实践,您需要首先检查密钥是否确实存在。

Write a helper function to get the parameter. You need to check if the key is actually present in the first place for good coding practices.

失与倦" 2024-11-21 05:47:24

从配置文件中提取的唯一“更有效”的方式是使用整个部分,然后迭代您想要的内容。当您最终得到循环代码时,它不太可能比您现在拥有的方法更有效。

用于简化的一种模式是创建“应用程序设置”单例并在应用程序加载时加载。您本质上是创建一个字符串、字符串的通用哈希表(字典等),这样您就可以更轻松地完成查找。但翻阅应用程序设置部分仍然存在开销。

The only "more efficient" manner to pull from a config file is to consume the entire section and then iterate through what you desire. As you end up with looping code, it is unlikely to be more efficient than the method you have now.

One pattern to use to simplify is to create an "App settings" Singleton and load at Application Load. You essentially create a generic hashtable (dictionary, etc.) of string, string, so you can accomplish lookups more easily. But there is still the overhead of ripping through the app settings section.

无人问我粥可暖 2024-11-21 05:47:24

您可能需要在类名上更有创意,但您可以按照以下方式做一些事情:

class ConfigManager
{
    public static string GetSetting(string name)
    {
        return ConfigurationManager.AppSettings[name].ToString();
    }
}

You need to be a bit more creative with the class name perhaps but you could do something along the lines of:

class ConfigManager
{
    public static string GetSetting(string name)
    {
        return ConfigurationManager.AppSettings[name].ToString();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文