我正在重构一个遗留应用程序,它使用一个巨大的模块(静态类)来存储它的全局状态。 400个不同的成员变量:
Public Module GlobalState
Public Variable1 As Single
Public Variable2 As Single
...
Public Variable400 As Single
如何以人类可读的格式(XML,JSON ......,而不是二进制转储)将所有这些变量的值转储到文件磁盘上?
常用的对象记录器需要该类的实例,但在这种情况下,一切都是静态的。
答案 0 :(得分:2)
如果我理解正确,可以通过反思来完成:
Imports System.Reflection
Imports System.Xml.Serialization
Imports System.IO
Private Sub Create()
Dim list As New List(Of GlobalStateItem)
For Each m As FieldInfo In GetType(GlobalState).GetFields(BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.Static Or BindingFlags.DeclaredOnly)
list.Add(New GlobalStateItem(m.Name, m.GetValue(Nothing)))
Next
Dim serializer As New XmlSerializer(GetType(List(Of GlobalStateItem)))
Using stream As New StreamWriter("path")
serializer.Serialize(stream, list)
End Using
End Sub
<Serializable()>
Public Structure GlobalStateItem
Public Sub New(name As String, value As Object)
Me.Name = name
Me.Value = value
End Sub
Public Name As String
Public Value As Object
End Structure
Public Module GlobalState
Public Variable1 As Single = 1.0!
Public Variable2 As Single = 2.0!
Public Variable400 As Single = 400.0!
End Module
输出:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfGlobalStateItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<GlobalStateItem>
<Name>Variable1</Name>
<Value xsi:type="xsd:float">1</Value>
</GlobalStateItem>
<GlobalStateItem>
<Name>Variable2</Name>
<Value xsi:type="xsd:float">2</Value>
</GlobalStateItem>
<GlobalStateItem>
<Name>Variable400</Name>
<Value xsi:type="xsd:float">400</Value>
</GlobalStateItem>
</ArrayOfGlobalStateItem>