代码之家  ›  专栏  ›  技术社区  ›  Wayne Werner

VB.NET重载数组访问?

  •  1
  • Wayne Werner  · 技术社区  · 14 年前

    是否可以在vb.net中重载array/dict访问运算符?例如,您可以声明如下内容:

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

    那就行了。但我想说的是:

    mydict("Cool guy") = "3"
    

    然后将3自动转换为整数3。

    我的意思是,当然我可以有一个私有成员mydict.coolguy,并有setcoolguy()和getcoolguy()方法,但是我可以 更喜欢 如果可能的话,可以用以前的方式写。

    谢谢


    为了澄清-我想能够“做有价值的事情”。例如,假设我有

    myclass.fizzlesticks ' String type
    myclass.thingone     ' Numerical type, say integer
    

    然后我想写

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

    它触发了一个类似于

    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
    

    这不是一个精确的用例,但我认为它能更好地说明我在寻找什么?

    2 回复  |  直到 10 年前
        1
  •  2
  •   Wayne Werner    14 年前

    不,不能在VisualBasic中重载数组访问运算符。

    Currently 唯一可以重载的运算符是:

    Unary operators:
    +   -   Not   IsTrue   IsFalse   CType
    
    Binary operators:
    +   -   *   /   \   &   Like   Mod   And   Or   Xor
    ^   <<   >>   =   <>   >   <   >=   <=
    
        2
  •  0
  •   Tommy    14 年前

    为什么你不能做以下工作:

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

    然后你可以做

    dim x =  mydict("Cool guy") + 7
    
    //x returns 10
    

    或者,你可以做一个int32.triparse

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