存儲爲XML,而不是
<?xml version="1.0" encoding="UTF-8"?>
<Components>
<Component name="Motor" cost="100" quantity="100" />
<Component name="Shaft" cost="10" quantity="100" />
</Components>
假設你有這樣的定義
public class AssembleComponent
{
public decimal Cost { get; set; }
public int Quantity { get; set; }
}
裝載方法
var components = new Dictionary<string, AssembleComponent>();
XDocument doc = XDocument.Load(@"C:\Users\Oli\Desktop\components.xml");
foreach (XElement el in doc.Root.Descendants()) {
string name = el.Attribute("name").Value;
decimal cost = Decimal.Parse(el.Attribute("cost").Value);
int quantity = Int32.Parse(el.Attribute("quantity").Value);
components.Add(name, new AssembleComponent{
Cost = cost, Quantity = quantity
});
}
然後,您可以訪問諸如組件這
AssembleComponent motor = components["Motor"];
AssembleComponent shaft = components["Shaft"];
注:在運行時調用編譯器動態地創建變量名,因爲你需要在編譯時就知道他們(或設計時,如果你喜歡)做一些與他們有用不是很有用。因此,我將這些組件添加到字典中。這是動態創建「變量」的好方法。
可能重複:http://stackoverflow.com/q/826398/380384 – ja72
這是不是一個真正的重複,因爲問題不從文件執行任意代碼行來解決。相反,只有值存儲在文件中,而不是代碼中。 –