从C#中的文本文件执行代码行 [英] Execute code lines from a text file in C#

查看:58
本文介绍了从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#中的文本文件执行代码行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆