0

我想达到与使用此语法在 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 框架 3.5!

谢谢!

4

2 回答 2

3

这里没问题:

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) 中。

对于早期版本:不,没有辅助方法是不可能的。

于 2012-08-22T11:56:09.273 回答
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
于 2012-08-22T11:58:11.590 回答