【发布时间】:2010-10-05 14:08:19
【问题描述】:
我已经使用 UpgradeWizard 将一些在自定义类型中使用固定长度字符串的 VB6 代码升级到 VB .NET,并且在使用 LSet 方法时遇到了问题,我希望有人能帮助我。
现有的 VB6 代码(类型声明);
Public Type MyType
PROP1 As String * 15
PROP2 As String * 25
End Type
Public Type MyTypeBuffer
Buffer As String * 40
End Type
用法示例;
LSet instOfMyTypeBuffer.Buffer = ...
LSet instOfMyType = instOfMyTypeBuffer
将其升级到 .NET 的合适方法是什么?
使用升级向导,我得到以下信息;
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
_
Public Structure MyType
<VBFixedString(15),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr,SizeConst:=15)> _
Dim PROP1 As FixedLengthString
<VBFixedString(25),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr,SizeConst:=25)> _
Dim PROP2 As FixedLengthString
Public Shared Function CreateInstance() As MyType
Dim result As New MyType
result.PROP1 = New FixedLengthString(15)
result.PROP2 = New FixedLengthString(25)
Return result
End Function
End Structure
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
_
Public Structure MyTypeBuffer
<VBFixedString(CLVHDR_REC_LENGTH),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr,SizeConst:=40)> _
Dim Buffer As FixedLengthString
Public Shared Function CreateInstance() As MyTypeBuffer
Dim result As New MyTypeBuffer
result.Buffer = New FixedLengthString(40)
Return result
End Function
End Structure
FixedLengthString 来自命名空间 Microsoft.VisualBasic.Compatibility.VB6。
升级向导失败的地方在于 LSet。它产生了以下内容;
instOfMyTypeBuffer.Buffer = LSet(...)
instOfMyType = LSet(instOfMyTypeBuffer)
编译失败,出现这些错误;
“字符串”类型的值不能 转换成 'Microsoft.VisualBasic.Compatibility.VB6.FixedLengthString'
没有为参数指定参数 “公共职能”的“长度” LSet(源为字符串,长度为 整数)作为字符串'
“MyTypeBuffer”类型的值不能 转换为“字符串”
所以,我可以使用 ToString() 来获得其中的一部分,但仍然存在 LSet 方法调用本身的问题。我应该怎么做才能重新创建原始功能?升级向导是否给了我一个完全不合适的转换,或者它是否可以挽救成可用的东西?
【问题讨论】:
-
这是不可挽救的,这种形式的 LSet 不再受支持,因为它会生成无法验证的代码。抛弃固定长度的字符串。
-
@Hans 你对LSet 的看法是正确的。但是在这里我认为
LSet只是被用作一种奇怪的方式来进行简单的字符串操作。我觉得很容易recode the manipulations in VB.Net -
我之前发布过类似的问题,可能相关:stackoverflow.com/questions/3863191/…
-
@Hans 您的其他答案在一般情况下看起来很棒。这是一种特殊情况,LSet 被滥用来分割由固定长度字符串组成的记录。
-
谢谢汉斯,我看了看你的其他答案,效果很好。但是,正如我在对 MarkJ 答案的评论中解释的那样,我决定将代码重新编写回安全世界。感谢您的建议,我从中学到了很多。
标签: .net vb6 vb6-migration