gpt4 book ai didi

c# - 可序列化字典,如何设置键名?

转载 作者:数据小太阳 更新时间:2023-10-29 01:48:30 26 4
gpt4 key购买 nike

问题:我使用一个可序列化的字典类,在 http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx, 序列化字典。哪个工作正常,但我遇到了一个烦人的问题。

      <System.Xml.Serialization.XmlRoot("DataBase")> _
Public Class cDataBase
<System.Xml.Serialization.XmlNamespaceDeclarations()> _
Public ns As New System.Xml.Serialization.XmlSerializerNamespaces()


<System.Xml.Serialization.XmlElement("Tables")> _
Public Tables1 As New SerializableDictionary(Of String, cTable)


End Class ' cDataBase

当我像这样序列化上述类的实例时,创建的 xml 如下所示:

<Tables>
<item>
<key>
<string>MyTable</string>
</key>
<value>
<Table CreationDate="0001-01-01T00:00:00" LastModified="0001-01-01T00:00:00">
<Columns>
<Column Name="PrimaryKeyName">
<DataType>Uniqueidentifier</DataType>
<Length>36</Length>
</Column>
</Columns>
<Rows>
<Row>
<Item>Reihe1</Item>
<Item>Reihe2</Item>
<Item>Reihe3</Item>
</Row>
<Row>
<Item>Reihe1</Item>
<Item>Reihe2</Item>
<Item>Reihe3</Item>
</Row>

如果我能弄清楚如何重命名 key ,那会很好 到属性中定义的内容

  <key>
<string>MyTable</string>
</key>

基本上类似于 XmlArrayItem 属性,如下所示,如果(仅)字典是一个数组...

        <System.Xml.Serialization.XmlArray("Tables")> _
<System.Xml.Serialization.XmlArrayItem("Table")> _
Public Tables As New List(Of cTable)

我想尝试将 Of String 更改为继承自 string 的自定义类,我可以为其配备一个名称,但问题是,不能继承自 string...

最佳答案

如果我没看错你的问题,你想改变你的序列化输出:

<Tables>
<item>
<key>
<string>MyTable</string>
</key>
<value>
<!-- snip -->
</value>
</item>
</Tables>

像这样:

<Tables>
<item>
<key>
<TableId>MyTable</TableId>
</key>
<value>
<!-- snip -->
</value>
</item>
</Tables>

您还提到实现此目的的一种方法是创建您自己的继承自 System.String 的类型,正如您还提到的那样,这显然是不可能的,因为它是 密封

不过,您可以通过将键值封装在您自己的类型中,然后使用 XmlTextAttribute 控制 XmlSerializer 输出来实现相同的结果(参见 MSDN):

By default, the XmlSerializer serializes a class member as an XML element. However, if you apply the XmlTextAttribute to a member, the XmlSerializer translates its value into XML text. This means that the value is encoded into the content of an XML element.

在您的情况下,您将使用如下属性:

public class TableId
{
[XmlText]
public string Name
{
get;
set;
}
}

然后使用此类型作为您的Dictionary 的键。哪个应该实现你想要的。

关于c# - 可序列化字典,如何设置键名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3264181/

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