[英]VB Serialisation to C# Serialisation
我在一家用VB编写程序的公司开始编程。 我将其转换为C#,因为它是更简洁的代码。
在VB中,他们做了这样的事情:
Class Program
Friend Shared Sub Main(args As String())
Dim obj As New Class1()
Dim fs As New System.IO.FileStream("test.txt", System.IO.FileMode.OpenOrCreate)
Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.Serialize(fs, obj)
fs.Close()
fs = New System.IO.FileStream("test.txt", System.IO.FileMode.OpenOrCreate)
bf = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
obj = bf.Deserialize(fs)
For Each item As String In obj.myList
Console.WriteLine(item)
Next
Console.Read()
End Sub
End Class
<Serializable> _
Class Class1
Public myList As List(Of String)
Public Sub New()
myList = New List(Of String)()
myList.Add(True)
myList.Add(False)
myList.Add(True)
myList.Add(False)
myList.Add(True)
myList.Add(False)
myList.Add(True)
End Sub
End Class
但是在C#中,绝对不允许将布尔值分配给String-Var。 我在C#中编写了一个名为Class1Old的类,该类包括VB中声明的所有成员,但是当我在C#中反序列化时,我捕获到异常“字符串无法转换为布尔值”。
我看着书面的* .txt文件,结果非常令人困惑:
ÿÿÿÿ JConsoleApplication1, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null
ConsoleApplication1.Class1
myListSystem.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
_items_size_version True False
我无法想象这7个值是如何转换和重新转换的。
我如何反序列化从VB编写的C#文件?
希望有人可以帮助我...
编辑:
现在,我将一个包含“旧”代码的VB dll项目添加到了我的项目中。 我的C#代码在VB代码中调用了一个方法,该方法开始反序列化。 但是我仍然收到ArgumentException:
The object of type "System.Collections.Generic.List`1[System.String]" can not be converted to type "System.Collections.Generic.List`1[System.Boolean]".
但是,在我的实际项目中,序列化类中的所有参数与纯VB项目中的参数类型相同。
那么,是什么原因导致异常呢?
问候亨里克
在VB.net中也禁止将布尔值分配给字符串变量-除非您的前任未使用Option Strict On。 在这种情况下,您的C#话语就是意思-编码实践有问题,而不是VB.Net。
没有简单的方法来反序列化该类-我认为最好的方法是Bool Properties,该布尔属性在设置时也会创建字符串变量。 这将与xml serialiazation一起使用,我不确定是否与Binary格式化程序一起使用。
如果您坚持要“修复”未损坏的内容,我想您将需要反序列化为一个中间的“翻译”类,该类的列表定义为“对象”或“布尔”。 然后,此类将输出Class1对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.