整数加一

Tim*_*mmy 3 vb.net

在 C# 中创建消息时,我做了类似的事情。

            ByteMessage[i] = "A"
            ByteMessage[++i] = "B"
            ByteMessage[++i] = "C"
            ......................
Run Code Online (Sandbox Code Playgroud)

我想在 VB.NET 中实现这一点,除了 VB.NET 不支持++or--运算符。我试过这样的事情

            ByteMessage(i += 1) = "A"
            ByteMessage(i += 1) = "B"
            ByteMessage(i += 1) = "C"
            ......................
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用。该MATH库似乎没有任何在它的任何使用。

在 VB.NET 中是否有像 C# 那样的干净解决方案?

TnT*_*nMn 5

.Net 中没有任何内在的东西支持前/后增量和返回功能。C# 编译器通过在编译代码时发出所需的 IL 语句来支持它。虽然 VB.Net 语言开发人员认为不需要此功能,但没有什么可以阻止您使用扩展方法添加此功能。

唯一的限制是您需要为扩展方法使用有效的方法名称(例如IncrPreor IncrPost),并使用方法表示法而不是++iori++表示法。

Public Module Int32Extensions
    <Extension()>
    Public Function IncrPost(ByRef i As Int32) As Int32
        Dim ret As Int32 = i
        i += 1
        Return ret
    End Function

    <Extension()>
    Public Function IncrPre(ByRef i As Int32) As Int32
        i += 1
        Return i
    End Function
End Module
Run Code Online (Sandbox Code Playgroud)

用法示例:

Dim i As Int32 = 0
Dim ByteMessage As String() = New String(0 To 4) {}
ByteMessage(i) = "A"
ByteMessage(i.IncrPre) = "B"
ByteMessage(i.IncrPre) = "C"
i = 3
ByteMessage(i.IncrPost) = "D"
ByteMessage(i) = "E"
Run Code Online (Sandbox Code Playgroud)

产量:

在此处输入图片说明