VB.net中的Mid作为左侧运算符有特殊(奇怪?)的行为

5
今天和同事聊天时,他说出了一些奇怪的想法。
他提到了一种处理来自vb6的字符串的“秘密”方法,大致如下:
 Dim strSomeString as String
 strSomeString = "i am phat" 
 Mid$(strSomeString, 6,4) = "hack"

这将把i am hack放入strSomeString中。

虽然对于VB6支持这样的奇特性感到惊讶,但当我读到它在VB.Net中也得到了支持时,我完全被吹走了(可能是为了与旧代码兼容)。

Dim TestString As String
' Initializes string.
TestString = "The dog jumps"
' Returns "The fox jumps".
Mid(TestString, 5, 3) = "fox"
' Returns "The cow jumps".
Mid(TestString, 5) = "cow"
' Returns "The cow jumpe".
Mid(TestString, 5) = "cow jumped over"
' Returns "The duc jumpe".
Mid(TestString, 5, 3) = "duck"

我的问题是: 它在技术上如何工作的?在这种特定情况下,Mid 起到了什么作用?(方法?函数?扩展方法?)


在我使用VB6的时候,我从未想到过这是可能的。请告诉我没有人故意在.Net中这样做! - Chris Pitman
1
没关系。这样做会异步地警告微软,微软会派遣坏人打败那个天才。 - Alex Bagnolini
1个回答

8
它被翻译为在Microsoft.VisualBasic.CompilerServices.StringType中调用此函数的MSIL。
Public Shared Sub MidStmtStr ( _
    ByRef sDest As String, _
    StartPosition As Integer, _
    MaxInsertLength As Integer, _
    sInsert As String _
)

这个编译器技巧纯粹是为了向后兼容。它内置于编译器中,因此不是您可以在自己的类型上实现的技巧。

因此,

Mid(TestString, 5, 3) = "fox"

变成

MidStmtStr(TestString, 5, 3, "fox")

希望这可以帮助您,

@Alex:很高兴能帮上你,伙计。 - Binary Worrier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接