【问题标题】:Create generic array in VB.NET在 VB.NET 中创建泛型数组
【发布时间】:2012-08-22 20:11:26
【问题描述】:

我想用这种语法在 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!

谢谢!

【问题讨论】:

  • '好吧,到目前为止你尝试了什么? VS 提供了一个非常方便的智能感知,如果使用得当,它真的很有帮助......
  • @BigYellowCactus,你是对的,但没有人说他不能访问谷歌,对吧?如果他至少尝试过将智能感知+谷歌结合起来,他很快就会得到答案,而不会在这里浪费我们和他的时间,你不觉得吗?现在他的问题看起来像 - hey, I need THIS, but I don't want to do it, so do it for me people!

标签: c# .net vb.net linq


【解决方案1】:

这里没问题:

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

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

【讨论】:

  • 它是否适用于 .NET 框架 3.5?我不确定......在这种情况下更紧凑!
  • 谢谢……但这不是为我运行的……它给出了一个错误,我无法编译!!
【解决方案2】:

我认为使用该框架没有紧凑的语法,就像在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-19
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    相关资源
    最近更新 更多