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

标签 .net vb.net

今天,在与我的同事交谈时,他的脑海中浮现出一些奇怪的东西。

处理来自 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/

相关文章:

c# - 抽象类和只读属性

c# - 为什么要创建一个新的委托(delegate)对象

c# - 使用反射调用属性的方法

c# - .NET 能否在运行时进行解析和评估

mysql - 不支持关键字 'data source'

c# - "Constrained Types"在 VB/C# 中有用吗?

c# - 我如何(优雅地)将文本框转置到字符串特定部分的标签上?

c# - 如何在具有相同端口的不同 IP 地址上运行 HttpListener 和 TcpListener?

c# - RC4 加密与预期不符

c# - 使用 Xsd 验证序列化 WCF 代理类中的 Xml 时缺少架构错误