【问题标题】:How do I save static strings to an XML file?如何将静态字符串保存到 XML 文件?
【发布时间】:2021-03-29 15:52:30
【问题描述】:

我正在尝试将多个静态字符串保存到一个 XML 文件中,但我查看的所有教程都没有显示如何保存字符串 - 更不用说静态字符串了。

我不知道关于 C# 编码的第一件事是没有帮助的。

public class Strings
{
  public static string string1 = "text1";
  public static string string2 = "text2";
  public static string string3 = "text3";
//I am dealing with way more than 3 strings, but I don't want to type out all of them
}

如何收集这些字符串,然后将它们保存为 XML 文件? 我认为这样的事情可能会奏效,但我怀疑它会不会

public class StringSaver
{
  foreach (static string in Strings)
  {
   savestring1 = Strings.string1;
   savestring2 = Strings.string2;
   savestring3 = Strings.string3;
  }

}

public class StringXML 
{
  XMLSerializer xmlstringsaver = new XMLSerializer(Typeof(StringSaver));

}

我打算将字符串保存到 XML 文件中,如果更改了一个或多个字符串,我希望也保存更改。 (编辑)我正在使用统一,如果这改变了任何东西

【问题讨论】:

  • let alone static ones 是否为静态字符串并不重要。值是一样的。静态字符串不是某种不同的对象或类型。静态只是意味着它与自身有关,而不是与实例有关。换句话说,要使用该变量,您不必创建类的实例。
  • 使用 IXmlSerializable。你会得到一个 Xmlreader 和 XmlWriter,你可以读/写任何类型的格式。请参阅:docs.microsoft.com/en-us/dotnet/api/…

标签: c# xml string unity3d serialization


【解决方案1】:

这可能不是最好的解决方案,但您可以将所有静态字符串保存到列表中,然后将其序列化:

List<string> l = new List<string>(); // If you want, you can use Dictionary, but XmlSerializer win't be able to serialize it
foreach (FieldInfo fi in typeof(Strings).GetFields().Where(p => p.IsStatic && (p.FieldType == typeof(string)) /*&& p.IsPublic*/))
    // this will go trough all static strings in Strings, you can uncomment the IsPublic if you want only public ones
{
    l.Add(fi.GetValue(new Strings()) as string); // this will add the value of the current static string to the List
    // in case you would use dictionary aou can use 'fi.Name' (name of the string) as key
}
// now l contains all static strings from Strings class, in the same order in which tey are defined in the Strings class, and you can do with it what you want
// here I serialized it using XmlSerializer
XmlSerializer s = new XmlSerializer(l.GetType());
string ser;
using (StringWriter writer = new StringWriter())
{
    s.Serialize(writer, l);
    ser = writer.ToString(); // ser will contain the serialized list
}

请记住,您需要添加这些引用:

using System.Collections.Generic; // for List
using System.IO; // for StringWriter
using System.Linq; // for function .Where to query only static strings
using System.Xml.Serialization; // for serialization
using System.Reflection; // for getting all fields from class Strings

可能有更好的方法来做到这一点(无需反射),但这无需您手动将所有字符串添加到列表中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多