简体   繁体   中英

Create generic array in VB.NET

I want to reach the same result as I obtain in C# with this syntax, but in 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;

...so, I just want to create a generic array in VB.

In C# it works well, but I don't kwon this VB.NET syntax...

I'm using .NET framework 3.5!

Thank you!

No problem here:

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

At least in .Net 4.0 (VB.Net 10.0).

For earlier versions: No, not possible without a helper method.

I think with that framework there's no compact syntax for that, as in C#...

Try using this way...

Declare a method like this (shared is better I think):

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

So you can create an array passing a generic parameter, than with LINQ should be easy to create a generic list:

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

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

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

return myList.Count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM