.net 在C#中执行文本文件中的代码行

relj7zay  于 2023-01-03  发布在  .NET
关注(0)|答案(6)|浏览(140)

我有一个文本文件看起来像:

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变量存储在内存中,以供以后计算。
我能做些什么来实现这一目标?

ut6juiuv

ut6juiuv1#

改为将其存储为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"];

注意:通过在运行时调用编译器来动态创建变量名并不是很有用,因为你需要在编译时(或者设计时,如果你喜欢的话)知道它们,才能对它们做一些有用的事情。因此,我将组件添加到字典中。这是动态创建“变量”的好方法。

rjee0c15

rjee0c153#

如果只是数据,不要使用平面文本文件,而是使用XML。
您可以将中的XML反序列化为对象并对它们执行必要的操作。

azpvetkf

azpvetkf4#

下面是我过去使用过的一些代码,它们可以完成你所需要的大部分任务,尽管你可能需要根据自己的具体需求进行调整。

  • 创建临时命名空间和该命名空间中的公共静态方法。
  • 将代码编译为内存中的程序集。
  • 提取已编译的方法并将其转换为委托。
  • 执行委托。

这时就像执行一个普通的静态方法一样,所以当您说希望将结果保存在内存中供以后使用时,您必须弄清楚它是如何工作的。

public void CompileAndExecute(string CodeBody)
{
    // Create the compile unit
    CodeCompileUnit ccu = CreateCode(CodeBody);

    // Compile the code 
    CompilerParameters comp_params = new CompilerParameters();
    comp_params.GenerateExecutable = false;
    comp_params.GenerateInMemory = true;
    comp_params.TreatWarningsAsErrors = true;
    comp_results = code_provider.CompileAssemblyFromDom(comp_params, ccu);

    // CHECK COMPILATION RESULTS
    if (!comp_results.Errors.HasErrors)
    {
        Type output_class_type = comp_results.CompiledAssembly.GetType("TestNamespace.TestClass");

        if (output_class_type != null)    
        {    
            MethodInfo compiled_method = output_class_type.GetMethod("TestMethod", BindingFlags.Static | BindingFlags.Public);    
            if (compiled_method != null)    
            {    
                Delgate created_delegate = Delegate.CreateDelegate(typeof(System.Windows.Forms.MethodInvoker), compiled_method);
                if (created_delegate != null)
                {
                    // Run the code
                    created_delegate.DynamicInvoke();
                }
            }
        }
    }
    else
    {
        foreach (CompilerError error in comp_results.Errors)
        {
            // report the error
        }
    }
}

public CodeCompileUnit CreateCode(string CodeBody)
{
    CodeNamespace code_namespace = new CodeNamespace("TestNamespace");

    // add the class to the namespace, add using statements
    CodeTypeDeclaration code_class = new CodeTypeDeclaration("TestClass");
    code_namespace.Types.Add(code_class);
    code_namespace.Imports.Add(new CodeNamespaceImport("System"));

    // set function details
    CodeMemberMethod method = new CodeMemberMethod();
    method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
    method.ReturnType = new CodeTypeReference(typeof(void));
    method.Name = "TestMethod";

    // add the user typed code
    method.Statements.Add(new CodeSnippetExpression(CodeBody));

    // add the method to the class
    code_class.Members.Add(method);

    // create a CodeCompileUnit to pass to our compiler
    CodeCompileUnit ccu = new CodeCompileUnit();
    ccu.Namespaces.Add(code_namespace);

    return ccu;
}
cuxqih21

cuxqih215#

您有两个主要选项:
1.展开文本,直到它成为有效的C#代码,然后编译并执行它
1.自己解析并执行它(即解释它)。

h79rfbju

h79rfbju6#

这可以通过以下步骤完成:一个月一次=〉一个月一次==〉一个月二次
可以按如下方式设计构件:

public bool RunMain(string code)
{
    const string CODE_NAMESPACE = "CompileOnFly";
    const string CODE_CLASS = "Program";
    const string CODE_METHOD = "Main";

    try
    {
        var code_namespace = new CodeNamespace(CODE_NAMESPACE);

        // add the class to the namespace, add using statements
        var  code_class = new CodeTypeDeclaration(CODE_CLASS);
        code_namespace.Types.Add(code_class);
        code_namespace.Imports.Add(new CodeNamespaceImport("System"));

        // set function details
        var method = new CodeMemberMethod();
        method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
        method.ReturnType = new CodeTypeReference(typeof(void));
        method.Name = CODE_METHOD;

        // add the user typed code
        method.Statements.Add(new CodeSnippetExpression(code));

        // add the method to the class
        code_class.Members.Add(method);

        // create a CodeCompileUnit to pass to our compiler
        CodeCompileUnit code_compileUnit = new CodeCompileUnit();
        code_compileUnit.Namespaces.Add(code_namespace);

        var compilerParameters = new CompilerParameters();
        compilerParameters.ReferencedAssemblies.Add("system.dll");
        compilerParameters.GenerateExecutable = true;
        compilerParameters.GenerateInMemory = true;
        compilerParameters.TreatWarningsAsErrors = true;

        var code_provider = CodeDomProvider.CreateProvider("CSharp");
        var comp_results = code_provider.CompileAssemblyFromDom(compilerParameters, code_compileUnit);

        if (comp_results.Errors.HasErrors)
        {
            StringBuilder sb = new StringBuilder();
            foreach (CompilerError error in comp_results.Errors)
            {
                sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
            }

                   
            throw new InvalidOperationException(sb.ToString());
        }

        //Get assembly, type and the Main method:
        Assembly assembly = comp_results.CompiledAssembly;
        Type program = assembly.GetType($"{CODE_NAMESPACE}.{CODE_CLASS}");
        MethodInfo main = program.GetMethod(CODE_METHOD);

        //runtit
        main.Invoke(null, null);
        return true;

    }
    catch(Exception compileException)
    {
        Console.Write(compileException.ToString());
        return false;
    }
}

在上面的代码中,我们实际上创建了一个简单的控制台Program.Main()

namespace CompileOnFly
{
    internal class Program
    {
       static void Main()
        {
            //<your code here>  
        }
    }
}

然后在内存中将其编译为可执行文件并执行。但是Main()主体//<your code here>是使用参数code动态添加到方法中的。
因此,如果文本文件script.txt中有一个脚本,如下所示:

Console.Write("Write your name: ");
var name = Console.ReadLine();
Console.WriteLine("Happy new year 2023 " + name);

您可以简单地读取所有文本并将其作为参数发送给它:

var code = File.ReadAllText(@"script.txt");
 RunMain(code);

运行script.txt文件中的语句。

相关问题