Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以在vb.net结构中定义赋值运算符吗?_Vb.net_Operators_Implementation_Value Type_Assignment Operator - Fatal编程技术网

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

我可以在vb.net结构中定义赋值运算符吗?,vb.net,operators,implementation,value-type,assignment-operator,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

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

我是这样定义的:

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

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

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
类型,我强烈建议您将其改为
缩小
运算符。这将强制代码的用户显式强制转换,这是一个可视化提示,表明赋值可能在运行时失败,例如

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

我问你是否可以让你的第一行工作,我想从这个80常数创建一个新的DeltaTime实例。我猜答案是“不,你不能”,但我认为同样的答案对C#也是有效的。我现在明白了。答案被重新编写。我想创建一个半字节类型,如果我试图将CType设置为高于&HF(半字节.最大值)的值,这应该是一个编译器错误,有可能吗?恐怕VB.NET语言不是这样工作的。如果您试图将一个大整数填充为一个小整数,那么它(a)需要您添加一个显式转换运算符,并且(b)在运行时发现任何转换失败。