【问题标题】:Error Cannot implicitly convert type错误无法隐式转换类型
【发布时间】:2018-07-11 09:51:33
【问题描述】:

以下是我在 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””。

我该如何解决这个问题?

【问题讨论】:

  • 将 List 更改为 ReadOnlyCollection。这是 FindElements 方法的返回值。

标签: c# xpath visual-studio-2017


【解决方案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(" ../"));

【讨论】:

    【解决方案2】:

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

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

    清楚吗?

    【讨论】:

      【解决方案3】:

      列表不等同于ReadOnlyCollection&lt;T&gt;,因此您要么必须使用类似的东西

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

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

      【讨论】:

        猜你喜欢
        • 2014-02-12
        • 2014-04-18
        • 1970-01-01
        • 1970-01-01
        • 2015-08-04
        • 2015-05-22
        • 2017-10-05
        • 1970-01-01
        相关资源
        最近更新 更多