繁体   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