Syntax error in `New SomeClass { Key .SomeProperty = SomeValue }` after C# -> VB conversion

筅森魡賤 提交于 2019-12-11 11:16:27

问题


A co-worker of mine and I both do programming. He has made a class in C# and I am working on converting it to VB.NET. I got the full class converted except for a single line, and at this point I cannot figure it out so thought a fresh set of eyes maybe able to find my error.

Original C# code

using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate })) 

Converted VB.NET code

Using client = New HttpClient(New HttpClientHandler With {Key .AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate})

Error Name of field or Property being initialized in an object initialize must start with '.'.

Error is located under the 'Key'

Last note: I used a dreaded code-converter for most of it, so I am unsure where 'key' came from.


回答1:


There are two concepts which have similar syntax but different semantics:

Anonymous Types

C#: new { A = 1, B = 2 }

VB: New With { Key .A = 1, Key .B = 2 }

Here, VB also allows you to add mutable (non-key) properties, which C# does not support:

New With { Key .A = 1, Key .B = 2, .SomeMutableProperty = 3 }

Hence, the Key keyword is important here.

Object Initializers for Named Types

C#: new MyClass { A = 1, B = 2 }

VB: New MyClass With { .A = 1, .B = 2 }

Here, existing properties of MyClass are set, so the Key keyword is irrelevant, and, thus, not allowed.


Apparently, your C# -> VB converter thought that this was an anonymous type, although it was an object initializer. Remove the Key keyword and send a bug report to the converter's developer.




回答2:


Not sure where the Key has come from.

Running this through Instant VB gives the following, so it would concur with my thought that the Key is not required:

Option Infer On

Using client = New HttpClient(New HttpClientHandler With {.AutomaticDecompression = DecompressionMethods.GZip Or DecompressionMethods.Deflate})


来源:https://stackoverflow.com/questions/35043458/syntax-error-in-new-someclass-key-someproperty-somevalue-after-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!