今天,在与我的同事交谈时,他的脑海中浮现出一些奇怪的东西。
处理来自 vb6 的字符串的“ secret ”方法,如下所示:
Dim strSomeString as String
strSomeString = "i am phat"
Mid$(strSomeString, 6,4) = "hack"
这会将 i am hack
放入 strSomeString
中。
虽然对 vb6 支持如此奇怪的东西感到惊讶,但当我读到 it is supported in VB.Net too 时我完全震惊了(可能是为了与旧代码兼容)。
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
的表现如何? (方法?函数?扩展方法?)
最佳答案
它被转换为 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")
希望这有帮助,
关于.net - VB.net Mid 作为左运算符特殊(奇怪?)行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1848099/