0

我有一个实际上是一个具有更多功能的简单字节的结构。我可以在vb.net Structure中定义一个赋值运算符吗?

我定义它是这样的:

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(半字节)stucture并使用它作为如下:

Dim myNibble As Int4 = &HF 'Unsigned 

回答

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 

UPDATE:

对于你提出的Int4型我强烈建议你让它Narrowing操盘手。这迫使你的代码的用户明确地进行转换,这是一个可视化的提示,表明该分配可能在运行时失败,例如,

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

我在问你是否可以让你的第一行工作,我想从这个常量创建一个DeltaTime的新实例。我想答案是“不,你不能”,但我认为同样的答案仍然适用于C#。 – Shimmy 2010-07-09 13:57:14

+0

我现在明白了。答案重写。 – 2010-07-09 14:00:21

+0

我想创建一个Nibble类型,如果我尝试将CType设置为高于&HF(Nibble.MaxValue)的值,它应该是编译器错误,是否有可能? – Shimmy 2010-07-22 10:49:22