gpt4 book ai didi

vb.net - 如何转储 VB.Net 模块所有成员的值?

转载 作者:行者123 更新时间:2023-12-01 09:31:57 26 4
gpt4 key购买 nike

我正在重构一个遗留应用程序,它使用一个巨大的模块(静态类)来存储它的全局状态。 400 个不同的成员变量:

Public Module GlobalState

Public Variable1 As Single
Public Variable2 As Single
...
Public Variable400 As Single

如何将所有这些变量的值以人类可读的格式(XML、JSON...,而不是二进制转储)转储到磁盘上的文件中?

常用的对象记录器需要一个类的实例,但在这种情况下一切都是静态的。

最佳答案

如果我理解正确的话,这可以通过反射(reflection)来完成:

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>

关于vb.net - 如何转储 VB.Net 模块所有成员的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21462434/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com