我有一个文本文件看起来像:
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变量存储在内存中,以供以后计算。
我能做些什么来实现这一目标?
6条答案
按热度按时间ut6juiuv1#
改为将其存储为XML
假设你有这个定义
像这样装
然后,您可以按如下方式访问组件
注意:通过在运行时调用编译器来动态创建变量名并不是很有用,因为你需要在编译时(或者设计时,如果你喜欢的话)知道它们,才能对它们做一些有用的事情。因此,我将组件添加到字典中。这是动态创建“变量”的好方法。
mv1qrgav2#
您可以使用
Microsoft.CSharp.CSharpCodeProvider
动态编译代码。具体来看一下CompileAssemblyFromFile。
rjee0c153#
如果只是数据,不要使用平面文本文件,而是使用XML。
您可以将中的XML反序列化为对象并对它们执行必要的操作。
azpvetkf4#
下面是我过去使用过的一些代码,它们可以完成你所需要的大部分任务,尽管你可能需要根据自己的具体需求进行调整。
这时就像执行一个普通的静态方法一样,所以当您说希望将结果保存在内存中供以后使用时,您必须弄清楚它是如何工作的。
cuxqih215#
您有两个主要选项:
1.展开文本,直到它成为有效的C#代码,然后编译并执行它
1.自己解析并执行它(即解释它)。
h79rfbju6#
这可以通过以下步骤完成:一个月一次=〉一个月一次==〉一个月二次。
可以按如下方式设计构件:
在上面的代码中,我们实际上创建了一个简单的控制台
Program.Main()
然后在内存中将其编译为可执行文件并执行。但是
Main()
主体//<your code here>
是使用参数code
动态添加到方法中的。因此,如果文本文件
script.txt
中有一个脚本,如下所示:您可以简单地读取所有文本并将其作为参数发送给它:
运行
script.txt
文件中的语句。