简体   繁体   English

VB.NET相当于匿名类型的C#对象初始化器

[英]VB.NET equivalent of C# object initializer of an anonymous type

I'm not experienced with advanced features of .NET type system. 我对.NET类型系统的高级功能没有经验。 I cannot find out of what type is zz (what can be written instead of var . Or is var the best choice here?) 我找不到zz的类型(可以写​​什么而不是var 。或者var是最好的选择吗?)

string foo = "Bar";
int cool = 2;
var zz = new { foo, cool };    // Watches show this is Anonymous Type

but most importantly, how the equivalent can be achieved in VB.NET code (this is what I actually need). 但最重要的是,如何在VB.NET代码中实现等效(这是我实际需要的)。

Dim Foo As String = "Bar"
Dim Cool As Integer = 2
Dim zz = {Foo, Cool}    'This is not an equivalent of above, I'm getting an array

I have searched several C# sources, used code watches and learned about how zz looks internally but I'm unable to make next step. 我搜索了几个C#源代码,使用了代码监视器并了解了zz在内部的运行方式,但我无法进行下一步。

(The purpose of my effort is something like this in VB.NET.) (我努力的目的是像这样在VB.NET)。

Your code would not even compile with OPTION STRICT set to ON which is highly recommended. 您的代码甚至不会在OPTION STRICT设置为ON的情况下编译,强烈建议使用。 No type can be derived from String + Int32 . 没有类型可以从String + Int32派生。 It would compile if you want an Object() : 如果你想要一个Object()它会编译:

Dim zz As Object() = {Foo, Cool}

But you want to create an anonymous type, use New With : 但是你想创建一个匿名类型,使用New With

Dim zz = New With {Foo, Cool}

http://msdn.microsoft.com/en-us/library/bb385125.aspx http://msdn.microsoft.com/en-us/library/bb385125.aspx


With .NET 4.7 and Visual Basic 2017 you can also use ValueTuples with names: 使用.NET 4.7和Visual Basic 2017,您还可以使用名称为ValueTuples

Dim zz = (FooName:=foo, CoolName:=cool)    

Now you can access the tuple items by name: 现在您可以按名称访问元组项:

int cool = zz.CoolName;

https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/data-types/tuples https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/data-types/tuples

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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