开发者

VB.NET overloading array access?

开发者 https://www.devze.com 2023-01-01 19:07 出处:网络
Is it possible to overload the array/dict access operators in VB.net? For example, you can state something like:

Is it possible to overload the array/dict access operators in VB.net? For example, you can state something like:

Dim mydict As New Hashtable()
mydict.add("Cool guy", "Overloading is dangerous!")
mydict("Cool guy") = "Overloading is cool!"

And that works just fine. But what I would like to do is be able to say:

mydict("Cool guy") = "3"

and then have 3 automagically converted to the Integer 3.

I mean, sure I can have a private member mydict.coolguy and have setCoolguy() and getCoolguy() methods, but I would prefer to be able to write it the former way if at all possible.

Thanks


To clarify - I want to be able to "do stuff" with the value. So for instance, say I have

myclass.fizzlesti开发者_如何学JAVAcks ' String type
myclass.thingone     ' Numerical type, say integer

and then I want to be able to write

myclass("thingummy") = "This is crazy"

which fires off a method that looks like this

Private sub insanitea(Byval somarg as Object, Byval rhs as Object)
    If somearg = "thingummy" And rhs = "This is crazy" Then
        thingone = 4
        fizzlesticks = rhs & " and cool too!"
    End If
End Sub

This isn't the precise use-case, but I think it does a better job of being able to illustrate what I'm looking for?


No, you can't overload the array access operators in Visual Basic.

Currently the only operators you can overload are:

Unary operators:
+   -   Not   IsTrue   IsFalse   CType

Binary operators:
+   -   *   /   \   &   Like   Mod   And   Or   Xor
^   <<   >>   =   <>   >   <   >=   <=


Why can't you do the following:

mydict("Cool guy") = 3 //without quotes

Then you can do

dim x =  mydict("Cool guy") + 7

//x returns 10

Or, you could do a Int32.tryParse

dim x as integer
if int32.tryParse(mydict("Cool guy"), x) then
     return x + 7 //would return 10
end if
0

精彩评论

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

关注公众号