从C#中的文本文件执行代码行

编程入门 行业动态 更新时间:2024-10-24 18:27:01
本文介绍了从C#中的文本文件执行代码行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个文本文件,如下所示:

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#中的文本文件执行代码行

本文发布于:2023-11-06 05:20:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562808.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!