我有一个名为Foo
的类,其属性如下:
Public Class Foo(Of T)
public Property Value as T
public Property Bar as Boolean
End Class
我有一个类型转换函数重载:
Public Shared Narrowing Operator CType(ins As [Foo](Of T)) As T
Return ins.Value
End Operator
Public Shared Widening Operator CType(prop As T) As [Foo](Of T)
Return New Foo(Of T) With {.Value = prop}
End Operator
我使用我的课程是这样的:
private Sub someSub()
Dim f as new Foo(of String)
f.Bar = True
f = "This is The Text"
// when doing this I lose the `Bar` beacuase of `Return New Foo(Of T) With {.Value = rightSide}` on `Widening` overload
End Sub
有什么办法可以保留该类的其他属性?
答案 0 :(得分:1)
怎么会有?当您分配给f
时,您将创建一个新的Foo(Of T)
对象,该对象对已经分配给该变量的对象的Bar
属性一无所知。您必须在运算符内部设置新对象的Bar
属性,但它对要将结果分配给的变量一无所知,因此也无法获得该值。要保留该属性值,您必须首先获取它,除了事先进行明显的手动检索然后再进行手动重置之外,您将无法获得它。