我一直在寻找类似问题的答案,在此过程中我偶然发现了这个问题。
实际上,约翰的回答为我指明了我需要去的方向。它也可能有助于解决原始问题:
我的问题:
我需要一些可以像整数一样使用的东西
Dim myVal as Integer
myVal = 15
If myVal = 15 then
...
End If
...等等...
但是我还需要额外的东西
myVal.SomeReadOnlyProperty (as String)
myVal.SomeOtherReadOnlyProperty (as Integer)
(实际上那些只读属性也可以是方法......)
等等...所以我真的需要一个对象
我正在考虑 Integer (@_@) 的扩展方法……我不想走那条路……
我也想过写一个“ReadOnlyPropertyOracle”作为一个单独的类,并给它类似的方法
GetSomeReadOnlyProperty(ByVal pVal as Integer) as String
GetSomeOtherReadOnlyProperty(ByVal pVal as Integer) as Integer
weeeell .... 这本来可以,但看起来很可怕...
于是出现了 John's Hack 和 Brian MacKay 对运营商的评论:
结合扩大/缩小转换运算符(用于赋值)和比较运算符用于...以及比较。
这是我的代码的一部分,它可以满足我的需要:
'The first two give me the assignment operator like John suggested
Public Shared Widening Operator CType(ByVal val As Integer) As MySpecialIntType
Return New MySpecialIntType(val)
End Operator
'As opposed to John's suggestion I think this should be Narrowing?
Public Shared Narrowing Operator CType(ByVal val As MySpecialIntType) As Integer
Return val.Value
End Operator
'These two give me the comparison operator
'other operators can be added as needed
Public Shared Operator =(ByVal pSpecialTypeParameter As MySpecialIntType, ByVal pInt As Integer) As Boolean
Return pSpecialTypeParameter.Value = pInt
End Operator
Public Shared Operator <>(ByVal pSpecialTypeParameter As MySpecialIntType, ByVal pInt As Integer) As Boolean
Return pSpecialTypeParameter.Value <> pInt
End Operator
是的,这仍然是 1-2 打单行运算符定义,但其中大多数都是微不足道的,几乎没有出错的余地 ;-) 所以这对我有用...