0

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

我是这样定义的:

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

有没有办法做到这一点?

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

当您想定义新的单例成员值类型(例如,您想定义一个半字节类型等)并且您希望能够通过分配给数字或其他语言来设置它时,我的问题也是有效的类型化的表示。

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

Dim myNibble As Int4 = &HF 'Unsigned
4

1 回答 1

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
于 2010-07-09T13:53:54.383 回答