c#条件对象声明

时间:2018-01-08 08:57:51

标签: c# .net compiler-errors

我想根据变量值声明一个对象。

这是我尝试运行但不编译的代码:

if (bcheck == 0)
    IWebDriver driver = new ChromeDriver();
else if (bcheck == 1)
    IWebDriver driver = new FirefoxDriver();
else if (bcheck == 2)
    IWebDriver driver = new InternetExplorerDriver();

如果我尝试编译代码,我会收到以下错误消息:

嵌入式声明不能是声明或带标签的声明

如何重写代码?

驱动程序对象在下面的代码中使用,我必须保留该名称,以便不改变程序流程。

4 个答案:

答案 0 :(得分:3)

IWebDriver driver = null;
if (bcheck == 0)
    driver = new ChromeDriver();
else if (bcheck == 1)
    driver = new FirefoxDriver();
else if (bcheck == 2)
    driver = new InternetExplorerDriver();

IWebDriver条件和if条件内的作业之外声明if

答案 1 :(得分:2)

您必须声明一个变量:

IWebDriver driver = null;
if (bcheck == 0)
   driver = new ChromeDriver();
else if (bcheck == 1)
   driver = new FirefoxDriver();
else if (bcheck == 2)
   driver = new InternetExplorerDriver();

答案 2 :(得分:2)

不要使用if / else,字典更简单,更易于扩展。

var dictionary = new Dictionary<int, IWebDriver>
{
    [0] = new ChromeDriver(),
    [1] = new FirefoxDriver(),
    [2] = new InternetExplorerDriver()
};

var driver = dictionary[bcheck];

答案 3 :(得分:1)

您可以在if-else语句之前声明driver,但只能在相关条件内对其进行初始化:

IWebDriver driver = null;
if (bcheck == 0)
    driver = new ChromeDriver();
else if (bcheck == 1)
    driver = new FirefoxDriver();
else if (bcheck == 2)
    driver = new InternetExplorerDriver();