错误无法隐式转换类型

时间:2018-07-11 09:51:33

标签: c# xpath visual-studio-2017

以下是我在Visual Studio 2017中的代码:

   private String generateXPATH(IWebElement childElement, String current)
            {
                String childTag = childElement.TagName;
                if (childTag.Equals("html"))
                {
                    return "/html[1]" + current;
                }
                IWebElement parentElement = childElement.FindElement(By.XPath(".."));
                List<IWebElement> childrenElements = parentElement.FindElements(By.XPath(" ../"));
                int count = 0;
                for (int i = 0; i < childrenElements.Count; i++)
                {
                    IWebElement childrenElement = childrenElements[i];
                    String childrenElementTag = childrenElement.TagName;
                    if (childTag.Equals(childrenElementTag))
                    {
                        count++;
                    }
                    if (childElement.Equals(childrenElement))
                    {
                        return generateXPATH(parentElement, "/" + childTag + "[" + count + "]" + current);
                    }
                }
                return null;
            }
        }
    }

在线

List<IWebElement> childrenElements = parentElement.FindElements(By.XPath(" ../"));

我收到以下错误:

  

“严重性代码描述项目文件行抑制状态   错误CS0029无法将类型'System.Collections.ObjectModel.ReadOnlyCollection'隐式转换为'System.Collections.Generic.List'“。

我该如何解决?

3 个答案:

答案 0 :(得分:1)

类型不匹配-如错误所示。

您有:

List<IWebElement> childrenElements = parentElement.FindElements(By.XPath(" ../"));

错误提示:

  

无法隐式转换类型   'System.Collections.ObjectModel.ReadOnlyCollection'到   'System.Collections.Generic.List'“。

因此,将childrenElements的类型更改为ReadOnlyCollection

ReadOnlyCollection<IWebElement> childrenElements = parentElement.FindElements(By.XPath(" ../"));

答案 1 :(得分:0)

列表不等同于ReadOnlyCollection<T>,因此您要么必须使用类似

IEnumberable<IWebElement> childElements = parentElement.FindElements(By.XPath(" ../"));

或使用var使用类型推断,或使用.ToList()获取要使用的列表。

答案 2 :(得分:0)

您正在尝试将ReadOnlyCollection关联到您的List变量。因此,有多种方法可以解决该问题。您可以将childrenElements的类型设为var,因此c#将为您选择该变量的类型。但是我不推荐这种类型的解决方案。或者,您可以在该行的末尾添加.ToList(),使其看起来像这样:

List<IWebElement> childrenElements = parentElement.FindElements(By.XPath(" ../")).ToList<IWebElement>();

清楚吗?