[英]Linq expression for ILIst works in VB.Net but not C#?
我當時正在轉換一些代碼,並使用Telerik的代碼轉換器,然后進行了臨時更改,但遇到了讓我有些困惑的事情。 我想讓它盡可能接近它,但是很好奇的最佳方法。 它出現
如果我想要一個通用的IList,可用於在WPF的從屬屬性中創建可能成為任何對象的IList的列表。 我可以在這樣的控制台應用程序中模擬它:
作品:
Private _listTest As IList
Public Property ListTest As IList
Get
Return _listTest
End Get
Set(ByVal value As IList)
_listTest = value
End Set
End Property
Sub Main()
ListTest = New List(Of Integer)({1, 2, 3, 4})
Dim items = From p In ListTest
End Sub
不起作用:
private static IList _listTest;
public static IList ListTest
{
get { return _listTest; }
set { _listTest = value; }
}
static void Main(string[] args)
{
ListTest = new List<int> { 1, 2, 3, 4 };
//Error:Could not find an implementation of the query pattern for source type 'IList'. 'Select' not found. Consider explicitly specifying the type of the range variable 'p'.
var items = from p in ListTest;
}
清單中的問題是等同於顯式的,這是針對泛型完成的。 我想我可以列出對象。 但是,在C#中是否有語言解決方案可以使其正常工作?
更緊密的C#LINQ查詢語法是將object
明確指定為范圍變量p
類型。 此外,我不知道VB.NET,但在C# select
需要(可以跳過只有當最后一個操作員group by
W / O into
條款):
var items = from object p in ListTest select p;
您應該考慮制作通用類型IList<object>
列表,或者每次嘗試在列表中使用Linq方法時,都應使用.OfType<T>
或.Cast<T>
。
var items = from p in ListTest.Cast<object>() select p;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.