假设我有一个item
,它有字段(属性)
- 地点
- 平均值
- 可用性
而且我有 10-15 items
,我想预定义其值,或者将其写入某处,然后加载到要使用的代码中。
哪个是最好的做法?
这些将是常量,只是启动参数,在应用程序生命周期中不会被修改。
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");
您的选择将是:
存储对象并在您的代码中读取它们。
编写 XML 代码示例:
public void WriteXML()
{
Book overview = new Book();
overview.title = "Serialization Overview";
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(Book));
System.IO.StreamWriter file = new System.IO.StreamWriter(
@"c:\temp\SerializationOverview.xml");
writer.Serialize(file, overview);
file.Close();
}
阅读 XML 代码示例:
public void Read(string fileName)
{
XDocument doc = XDocument.Load(fileName);
foreach (XElement el in doc.Root.Elements())
{
Console.WriteLine("{0} {1}", el.Name, el.Attribute("id").Value);
Console.WriteLine(" Attributes:");
foreach (XAttribute attr in el.Attributes())
Console.WriteLine(" {0}", attr);
Console.WriteLine(" Elements:");
foreach (XElement element in el.Elements())
Console.WriteLine(" {0}: {1}", element.Name, element.Value);
}
}
ApplicationSettings非常适合启动常量。
你所描述的听起来像是完美的用例T4
您可以将 T4 模板添加到您的项目中,该模板读取 XML 数据(在 Visual Studio 中的设计时)并使用您的静态内容生成 *.cs 文件。如果您需要修改数据,只需修改 XML 文件并单击Transform All Templates
解决方案资源管理器中的按钮。
请记住,如果您需要修改这些内容,这将需要您重新编译和重新部署应用程序。如果是这种情况,那么@Mortalus 提供的解决方案是最好的选择。
我会使用 web.config 并将其存储在应用程序设置区域中,然后创建一个类来读取这些将其作为列表检索。
这是它在 Web 配置和 C# 代码中的外观。
<appSettings>
<add key="location_1" value="123"/>
<add key="avgValue_1" value="123"/>
<add key="usability_1" value="123"/>
<add key="location_2" value="123"/>
<add key="avgValue_2" value="123"/>
<add key="usability_2" value="123"/>
<add key="count" value="2"/>
</appSettings>
public class SomeClass
{
private string location;
private double avgValue;
private int usability;
public string Location
{
get { return location; }
set { location = value; }
}
public double AvgValue
{
get { return avgValue; }
set { avgValue = value; }
}
public int Usability
{
get { return usability; }
set { usability = value; }
}
}
public class Config
{
public static List<SomeClass> Items
{
get
{
List<SomeClass> result = new List<SomeClass>();
for (int i = 1; i <= Convert.ToInt32(WebConfigurationManager.AppSettings["count"]); i++)
{
SomeClass sClass = new SomeClass();
sClass.AvgValue = Convert.ToDouble(WebConfigurationManager.AppSettings["avgValue_" + i.ToString()]);
sClass.Location = WebConfigurationManager.AppSettings["location_" + i.ToString()];
sClass.Usability = Convert.ToInt32(WebConfigurationManager.AppSettings["usability_" + i.ToString()]);
}
return result;
}
}
}