2010-06-02 57 views
1

是否有可能重载VB.net中的数组/字典访问操作符?例如,你可以说类似于:VB.NET重载数组访问?

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 

的方法这不是确切的用例,但我认为它能够更好地说明我在寻找什么?

+0

我花了刺伤你问什么,但不知道问题的标题和我读coorespond。让我知道,如果我在这里的基础。 – Tommy 2010-06-02 17:50:20

+0

这可能与我的例子一样准确,如果这些都是我需要的,那么您的解决方案可以很好地工作。我只想在我的课堂中稍微复杂一点,即在分配时我希望能够转换这些值,如果它们不是它们应该是的。如果那有意义的话... – 2010-06-02 17:59:02

回答

2

不,你不能重载Visual Basic中的数组访问运算符。

Currently你可以重载的唯一运营商:

Unary operators: 
+ - Not IsTrue IsFalse CType 

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

为什么你不能做到以下几点:

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

然后,你可以做

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

//x returns 10 

或者,你可以做一个Int32.tryParse

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