开发者

Bang vs Default Property in Visual Basic

For a given class, with a defau开发者_如何学Golt property of list, you can access an instance object in the list by doing myClass.defProperty("key"). You can also achieve the same results by typing myClass.defProperty!Key.

I have been told that using the parenthesis and quotes is faster for the way the runtime accesses the Property, but I'd like to understand what is the difference and how do each work...

I understand C# has a similar behavior by replacing the parenthesis with square brackets.


Given the following code in Visual Basic.NET:

Dim x As New Dictionary(Of String, String)
x.Item("Foo") = "Bar"

You can access the "Foo" member of the dictionary using any of the following:

Dim a = x!Foo
Dim b = x("Foo")
Dim c = x.Item("Foo")

If you look at the IL under Reflector.NET then you'll find that they all translate to:

Dim a As String = x.Item("Foo")
Dim b As String = x.Item("Foo")
Dim c As String = x.Item("Foo")

So, they are all equivalent in IL and, of course, they all execute at the same speed.

The bang operator only lets you use statically defined keys that conform to the standard variable naming rules.

Using the indexed approaches then your keys can be almost any valid value (in this case string) and you can use variables to represent the key.

For code readability I would recommend the x.Item("Foo") notation as is is very clear as to what is going on. x("Foo") can be confused with a call to a procedure and x!Foo makes the Foo look like a variable and not a string (which it really is). Even the Stack Overflow color-coding makes the Foo look like a keyword!

The C# equivalent for this code is x["Foo"];. There is no ! syntax equivalent.

So, the bottom-line is that ! isn't better or worse on performance and just may make code maintenance more difficult so it should be avoided.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜