假设我有item
,其中包含字段(属性)
我有10-15 items
,我想要预定义其值,或者在某处写入然后加载到要使用的代码中。
哪种方法最适合呢?
修改 这些是常量,只是启动参数,在应用程序生命周期中不会被修改。
答案 0 :(得分:2)
您的选择将是:
存储对象并将其读取到代码中。
编写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);
}
}
答案 1 :(得分:2)
您可以使用此帮助程序类将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");
答案 2 :(得分:1)
ApplicationSettings非常适合启动常量。
答案 3 :(得分:0)
您所描述的内容听起来像是T4
您可以在项目中添加一个读取XML数据的T4模板(在Visual Studio中的设计时),并使用您的静态内容生成* .cs文件。如果您需要修改数据,只需修改XML文件并单击解决方案资源管理器中的Transform All Templates
按钮。
请记住,如果您需要修改这些内容,则需要重新编译和重新部署应用程序。如果是这种情况,那么@Mortalus提供的解决方案是最好的选择。
答案 4 :(得分:0)
我将使用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;
}
}
}