我可以在vb.net结构中定义赋值运算符吗?

时间:2010-07-09 13:50:49

标签: vb.net operators implementation value-type assignment-operator

我的结构实际上是一个具有更多功能的简单字节。

我这样定义:

Structure DeltaTime

    Private m_DeltaTime As Byte
    Public ReadOnly DeltaTime As Byte
        Get
            Return m_DeltaTime
        End Get
    End Property

End Structure

我想拥有这两个功能:

Public Sub Main
    Dim x As DeltaTime = 80 'Create a new instance of DeltaTime set to 80
    Dim y As New ClassWithDtProperty With { .DeltaTime = 80 }
End Sub

有没有办法实现这个目标?

如果有一种方法可以从Structure继承,我只会继承Byte添加我的功能,基本上我只需要一个带有自定义功能的字节结构。

当您想要定义新的单例成员值类型(例如,您想要为例如定义半字节类型等)并且您希望能够使用赋值给数字设置它时,我的问题也是有效的或其他语言类型的表示。

换句话说,我希望能够定义以下Int4(半字节)结构并按如下方式使用它:

Dim myNibble As Int4 = &HF 'Unsigned

1 个答案:

答案 0 :(得分:2)

创建转换运算符,例如

Structure DeltaTime

    Private m_DeltaTime As Byte
    Public ReadOnly Property DeltaTime() As Byte
        Get
            Return m_DeltaTime
        End Get
    End Property

    Public Shared Widening Operator CType(ByVal value As Byte) As DeltaTime
        Return New DeltaTime With {.m_DeltaTime = value}
    End Operator

End Structure

<强>更新

对于您提议的Int4类型,我强烈建议您改为Narrowing运算符。这会强制显式转换代码的用户,这是一种视觉暗示,即赋值可能在运行时失败,例如。

Dim x As Int4 = CType(&HF, Int4) ' should succeed
Dim y As Int4 = CType(&HFF, Int4) ' should fail with an OverflowException