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

今天,在与我的同事交谈时,脑子里出现了一些奇怪的东西.

处理来自vb6的字符串的“秘密”方式,如:

Dim strSomeString as String
 strSomeString = "i am phat" 
 Mid$(strSomeString,6,4) = "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,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,3) = "fox"

MidStmtStr(TestString,3,"fox")

希望这可以帮助,

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐