LINQ to XML 中的 InvalidCastException
我正在使用 LINQ to XML 从资源中获取一些数据,这里我有一个函数,我在其中获取一些值,然后创建一个新对象(类型翻译),因此当我调用该函数时,我会得到一个翻译对象。现在我有了这段代码:
Public Shared Function RetrieveTranslation(ByVal file As String) As List(Of clsTranslation)
Dim valuetrans = From vl In XElement.Load(file).Elements("data") Select (New clsTranslation With {.Filename = file, .Value = vl.Element("value").Value, .TranslationId = vl.Attribute("name").Value})
Return valuetrans
End Function
问题是,使用这段代码我得到了这个错误: 无法将“WhereSelectEnumerableIterator2[System.Xml.Linq.XElement,clsTranslation]”类型的对象转换为“System.Collections.Generic.List
1[clsTranslation]”类型。
你知道它的投射方法吗? 预先感谢,
阿方索。
I am using LINQ to XML to take some data from resources , and here I have a function, where I take some values and then I create a new object (Type Translation), so when I call the function I get a Translation object. By now I have this code:
Public Shared Function RetrieveTranslation(ByVal file As String) As List(Of clsTranslation)
Dim valuetrans = From vl In XElement.Load(file).Elements("data") Select (New clsTranslation With {.Filename = file, .Value = vl.Element("value").Value, .TranslationId = vl.Attribute("name").Value})
Return valuetrans
End Function
The problem is that with this code I got this error:
Unable to cast object of type 'WhereSelectEnumerableIterator2[System.Xml.Linq.XElement,clsTranslation]' to type 'System.Collections.Generic.List
1[clsTranslation]'.
Do you know the way to cast it?
Thanks in advance,
Alfonso.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您在打开 Option Strict 的情况下进行编译,您就会在编译时发现这一点。
您无需强制转换它 - 您对结果调用
ToList()
,以从IEnumerable
创建一个List
。(我还建议您放弃
cls
前缀;它违反了 .NET 命名约定。)这样会留下:
If you were compiling with Option Strict on, you'd have found this out at compile time.
You don't cast it - you call
ToList()
on the result, to create aList<clsTranslation>
from theIEnumerable<clsTranslation>
.(I'd also advise you to ditch the
cls
prefix; it goes against the .NET naming conventions.)That would leave: