[英]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: 我想达到与使用这种语法在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;
...so, I just want to create a generic array in VB. ...所以,我只想在VB中创建一个通用数组。
In C# it works well, but I don't kwon this VB.NET syntax... 在C#中效果很好,但我不了解这种VB.NET语法...
I'm using .NET framework 3.5! 我正在使用.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). 至少在.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#... 我认为在该框架中没有紧凑的语法,就像在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: 因此,您可以创建一个传递通用参数的数组,而使用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.