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

May*_*aya 5 c# selenium app-config visual-studio

selenium = new DefaultSelenium(
    ConfigurationManager.AppSettings["TestMachine"].ToString(),
    4444,       
    ConfigurationManager.AppSettings["Browser"].ToString(),        
    ConfigurationManager.AppSettings["URL"].ToString()
);
Run Code Online (Sandbox Code Playgroud)

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

ConfigurationManager.AppSettings[""].ToString()
Run Code Online (Sandbox Code Playgroud)

Sta*_*eev 4

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

public interface IConfigurationService
{
    string GetValue(string key);
}
Run Code Online (Sandbox Code Playgroud)

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

所以你可以继续:

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

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

config["Browser"]
Run Code Online (Sandbox Code Playgroud)