vb.net之如何在 VB.net(使用结构类型)中从 VB6 重写 "LSet"
lonelyxmas
阅读:69
2025-06-02 22:19:02
评论:0
我有一个 VB6 应用程序,它使用 LSet()
和两种用户定义的数据类型 (Type),将数据从一种类型分配给另一种类型,例如:
Lset type1 = Type2
现在我必须在 VB.net 中应用等效逻辑。但是,在 VB.net 中,LSet cannot be used against different types (在 VB6 中键入)。
如何在 VB.net 中实现 VB6 LSet 逻辑?
示例/典型代码:
Public MQ_Policy As typPolicyDataRetrieval
Public typPolicyDataBlock As gtypPolicyDataBlock
With MQ_Policy.Input
.PcPolicyIDNum = Mid(InputString, 1, 8)
.PcPolicyIDNumPrefix = " "
.Datalength = Format$(CLng(Len(MQ_Policy)) - (Len(MQ_Policy.MQHeader) + Len(MQ_Policy.Input.Datalength)), String$(Len(.Datalength), "0"))
End With
LSet typPolicyDataBlock = MQ_Policy
感谢您的所有帮助。
请您参考如下方法:
你不应该在 VB.NET 中这样做。
还有其他方法,比如定义从一种类型到另一种类型的转换运算符,然后在代码中使用它们:
Private Structure t1
Public a As Short
Public b As Short
End Structure
Private Structure t2
Public v As Integer
Public Shared Widening Operator CType(ByVal v As t1) As t2
Return New t2 With {.v = v.a Or (CType(v.b, Integer) << 16)}
End Operator
End Structure
Sub Main()
Dim v1 As t1, v2 As t2
v2 = v1 ' Works!
End Sub
但是,如果您非常确定应该执行按字节复制,并且您知道 alignment issues并且对他们感到满意,那么您可以这样做:
Imports System.Runtime.InteropServices
Public Function CopyStructure(ByVal s As Object, ByVal ResultType As System.Type) As Object
Dim h As GCHandle
Try
h = GCHandle.Alloc(s, GCHandleType.Pinned)
Return Marshal.PtrToStructure(h.AddrOfPinnedObject, ResultType)
Finally
If h.IsAllocated Then h.Free()
End Try
End Function
Sub Main()
Dim v1 As t1, v2 As t2
v2 = DirectCast(CopyStructure(v1, GetType(t2)), t2)
End Sub
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。