gpt4 book ai didi

c# - 在哪里存储将在我的应用程序中使用的常量对象

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

假设我有一个item,它有字段(属性)

  1. 地点
  2. 平均值
  3. 可用性

我有 10-15 个,我想预定义它们的值,或者写在某个地方然后加载到要使用的代码中。

哪个是最佳实践?

这些将是常量,只是启动参数,在应用程序生命周期中不会被修改。

最佳答案

您可以序列化和反序列化 List<Item>使用此辅助类往返于 XML 文件:

public static class XmlHelper
{
// Specifies whether XML attributes each appear on their own line
const bool newLineOnAttributes = false;

public static bool NewLineOnAttributes { get; set; }
/// <summary>
/// Serializes an object to an XML string, using the specified namespaces.
/// </summary>
public static string ToXml(object obj, XmlSerializerNamespaces ns)
{
Type T = obj.GetType();

var xs = new XmlSerializer(T);
var ws = new XmlWriterSettings { Indent = true, NewLineOnAttributes = newLineOnAttributes, OmitXmlDeclaration = true };

var sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb, ws))
{
xs.Serialize(writer, obj, ns);
}
return sb.ToString();
}

/// <summary>
/// Serializes an object to an XML string.
/// </summary>
public static string ToXml(object obj)
{
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
return ToXml(obj, ns);
}

/// <summary>
/// Deserializes an object from an XML string.
/// </summary>
public static T FromXml<T>(string xml)
{
XmlSerializer xs = new XmlSerializer(typeof(T));
using (StringReader sr = new StringReader(xml))
{
return (T)xs.Deserialize(sr);
}
}

/// <summary>
/// Serializes an object to an XML file.
/// </summary>
public static void ToXmlFile(Object obj, string filePath)
{
var xs = new XmlSerializer(obj.GetType());
var ns = new XmlSerializerNamespaces();
var ws = new XmlWriterSettings { Indent = true, NewLineOnAttributes = NewLineOnAttributes, OmitXmlDeclaration = true };
ns.Add("", "");

using (XmlWriter writer = XmlWriter.Create(filePath, ws))
{
xs.Serialize(writer, obj);
}
}

/// <summary>
/// Deserializes an object from an XML file.
/// </summary>
public static T FromXmlFile<T>(string filePath)
{
StreamReader sr = new StreamReader(filePath);
try
{
var result = FromXml<T>(sr.ReadToEnd());
return result;
}
catch (Exception e)
{
throw new Exception(e.InnerException.Message);
}
finally
{
sr.Close();
}
}
}

用法:

XmlHelper.ToXmlFile(myList, @"c:\folder\file.xml");

var list = XmlHelper.FromXmlFile<List<Item>>(@"c:\folder\file.xml");

关于c# - 在哪里存储将在我的应用程序中使用的常量对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15257193/

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