我有一个文本文件,如下所示:
I have a text file looks like:
AssembleComponent Motor = new AssembleComponent; AssembleComponent Shaft = new AssembleComponent; ...... Motor.cost = 100; Motor.quantity = 100; Shaft.cost = 10; Shaft.quantity = 100; ......我希望在C#中执行这些代码行,以便将这些Motor.cost,Motor.quantity,Shaft.cost,Shaft.quantity变量存储在内存中,以便以后进行计算.
I wish to execute these code lines in C#, so that I will have these Motor.cost, Motor.quantity, Shaft.cost, Shaft.quantity variables stored in the memory for later calculation.
我该怎么做?
推荐答案将其存储为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 }); }然后您可以访问像这样的组件
You can then access the components like this
AssembleComponent motor = components["Motor"]; AssembleComponent shaft = components["Shaft"];注意:通过在运行时调用编译器动态创建变量名不是很有用,因为您需要在编译时(或设计时,如果愿意)知道它们,以对它们进行有用的处理.因此,我将组件添加到字典中.这是动态创建变量"的好方法.
Note: Creating the variable names dynamically by calling the compiler at runtime is not very useful since you need to know them at compile-time (or design-time if you prefer) to do something useful with them. Therefore, I added the components to a dictionary. This is a good way of creating "variables" dynamically.
更多推荐
从C#中的文本文件执行代码行
发布评论