【问题标题】:Can I define an assignment operator in vb.net Structure?我可以在 vb.net 结构中定义赋值运算符吗?
【发布时间】:2011-03-13 21:30:50
【问题描述】:

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

我是这样定义的:

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

有没有办法做到这一点?

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

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

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

Dim myNibble As Int4 = &HF 'Unsigned

【问题讨论】:

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


    【解决方案1】:

    创建一个转换运算符,例如

    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
    

    【讨论】:

    • 我在问你是否可以让你的第一行工作,我想从这个 80 常量创建一个新的 DeltaTime 实例。我想答案是“不,你不能”,但我认为同样的答案对 C# 仍然有效。
    • 我现在明白了。答案重写。
    • 我想创建一个 Nibble 类型,如果我尝试将 CType 设置为高于 &HF (Nibble.MaxValue) 的值,它应该是编译器错误,有可能吗?
    • 恐怕这不是 VB.NET 语言的工作方式。如果您尝试将一个大整数填充到一个较小的整数中,那么它 (a) 需要您添加一个显式转换运算符,并且 (b) 在运行时发现任何转换失败。
    猜你喜欢
    • 1970-01-01
    • 2015-03-05
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    相关资源
    最近更新 更多