可以说我有一个项目
,其中有场(属性)
Lets say I have an item
, which has fields(properties)
和我有10-15 项目
,我想predefined,或书面的地方,然后加载到code使用其值。
And I have 10-15 items
, whose values I want to be predefined, or written somewhere and then loaded into code to be used.
这将是最好的做法呢?
编辑: 这将是常量,刚启动的参数,它不会在应用程序生命周期进行修改。
These would be constants, just start up parameters, which will not be modified during application lifecycle.
您可以序列化和反序列化名单,其中,使用这个辅助类
并从XML文件;项目&GT
You can serialize and deserialize a List<Item>
to and from an XML file using this helper class:
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");