C#无法转换为&#39; string&#39;到&#39; System.Action <string>&#39;

时间:2017-10-14 16:38:51

标签: c# selenium selenium-webdriver

我试图在列表中的每个实例上运行一个方法,但是当我尝试使用&#34; .foreach()&#34;方法,我收到错误

  

&#34;无法转换为&#39; string&#39;到&#39; System.Action&#39;&#34;

我试图打电话的方法

public static string CheckSerial(List <string> serial, IWebDriver Driver)
{
    Driver.Navigate().GoToUrl("http://www.dell.com/support/home/uk/en/ukdhs1/product-support/servicetag/" + serial);
    return Driver.Title;
}

我的主要方法

static void Main(string[] args)
{       
    IWebDriver driver = new FirefoxDriver();

    List<string> serials = new List<string>
    {
        "JPV6Q12",
        "JPV7Q12"
    };
    serials.ForEach(CheckSerial(serials, driver));
};

先谢谢大家对此有任何帮助, 的问候,

1 个答案:

答案 0 :(得分:1)

List<string>.ForEach期待Action<string>作为参数,但这不是您传递的参数。

你应该这样称呼它:

public static string CheckSerial(string serial, IWebDriver Driver)
{
    Driver.Navigate().GoToUrl("http://www.dell.com/support/home/uk/en/ukdhs1/product-support/servicetag/" + serial);
    return Driver.Title;
}

serials.ForEach(s => CheckSerial(s, driver));

但奇怪的是,你对返回值一无所知。如果你想使用它并且GoToUrl在网址无效的情况下不会抛出异常,那么你可以:

var result = serials.Select(s => new { Serial = s, Title = CheckSerial(s, driver) });

如果您确实希望ForEach与您最初的工作方式类似,那么您可以将CheckSerial作为一种扩展方法,并且:

public static void CheckSerial(this IWebDriver Driver, string serial) { ... }
serials.ForEach(driver.CheckSerial);