无法隐式转换类型system.colllections.generic [英] Cannot implicitly convert type system.colllections.generic
问题描述
我遇到以下错误:
不能将类型'System.Collections.Generic.List>隐式转换为'System.Collections.Generic.List
Cannot implicitly convert type 'System.Collections.Generic.List>' to 'System.Collections.Generic.List
我的代码是:
class Check
{
public string Text { get; set; }
public List<Check> getxml()
{
XDocument xdoc = XDocument.Load(@"D:\Web Utf-8 Converter\Categories.xml");
var list = (from p in xdoc.Descendants("Categories")
select p.Elements("name"));
var listing = list.ToList();
return listing;
}
}
在我看来,这就像转换错误.但是我不确定如何转换.请协助.
This seems to me like a conversion error. But I'm not sure how to convert. Kindly assist.
谢谢.
推荐答案
select语句返回System.Xml.Linq.XElement.您的方法的返回类型为List.这些不一样.
the select statement is returning a System.Xml.Linq.XElement. The return type of your method is List. These are not the same.
您可以做的是:
var list = (from p in xdoc.Descendants("Categories")
select new Check { Text = p.Elements("name").Value});
但是我认为您的班级Check不应读取xml并存储每个元素的结果.
However I think your class Check should not read the xml and store the results of each element.
您应该宁愿拥有一个具有GetXml方法的"XmlParser"类和一个拥有该信息的"XmlValue"类.即
You should rather have a class "XmlParser" which has the GetXml Method and a class "XmlValue" which holds the information. i.e.
public class XmlValue
{
public System.Xml.Linq.XElement Element { get; set; }
public string Text
{
get
{
if(Element == null) return null;
return Element.Value;
}
}
}
public class XmlParser
{
public List<XmlValue> GetXml()
{
XDocument xdoc = XDocument.Load(@"D:\Web Utf-8 Converter\Categories.xml");
return xdoc
.Descendants("Categories")
.SelectMany(p => p.Elements("name"))
.Select(p => new XmlValue { Element = p });
.ToList();
}
}
void Main()
{
XmlParser parser = new XmlParser();
var list = parser.GetXml();
foreach(var el in list)
Console.WriteLine(el.Text);
}
这篇关于无法隐式转换类型system.colllections.generic的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!