簡體   English   中英

在VB.NET中創建通用數組

[英]Create generic array in VB.NET

我想達到與使用這種語法在C#中獲得的結果相同的結果,但是在VB.NET中:

// This is my generic object (coming from Json parsing!):
var genericContent = new { Name = "name1", Value = 0 };

// I would like to have a generic list, created by this generic item:
var myList = (new[] { genericContent }).ToList();

// So, I can add any other generic items (with the same structure)...
myList.Add(new { Name = "name2", Value = 1 });

// And treat them as a normal list, without declaring the class!
return myList.Count;

...所以,我只想在VB中創建一個通用數組。

在C#中效果很好,但我不了解這種VB.NET語法...

我正在使用.NET Framework 3.5!

謝謝!

沒問題:

Dim genericContent = new with { .Name = "name1", .Value = 0 }
Dim myList = {genericContent}.ToList()
myList.Add(new with { .Name = "name2", .Value = 1 })

至少在.Net 4.0(VB.Net 10.0)中。

對於早期版本:不,如果沒有輔助方法,則不可能。

我認為在該框架中沒有緊湊的語法,就像在C#中一樣。

嘗試使用這種方式...

聲明這樣的方法(我認為最好共享):

Public Shared Function GetArray(Of T)(ByVal ParamArray values() As T) As T()
    Return values
End Function

因此,您可以創建一個傳遞通用參數的數組,而使用LINQ則更容易創建通用列表:

Dim genericContent = New With { Name = "name1", Value = 0 }

Dim myList = (GetArray(genericContent)).ToList()

myList.Add(New With { Name = "name2", Value = 1 })

return myList.Count

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM