如何使用C#在.NET中运行时创建CLASS? [英] How to create a CLASS at runtime in .NET using C#?

查看:119
本文介绍了如何使用C#在.NET中运行时创建CLASS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何在c#中动态创建一个类?我试过下面的代码,但我无法找到它保存的地方



我尝试过:



how can we create a class dynamically in c#? I have tried with below code but I am unable to find where it saves

What I have tried:

static void Main()
    {
        TestExpression("2+1-(3*2)+8/2");
        TestExpression("1*2*3*4*5*6");
        TestExpression("Invalid expression");
    }
    static void TestExpression(string expression)
    {
        try
        {
            int result = EvaluateExpression(expression);
            Console.WriteLine("'" + expression + "' = " + result);
        }
        catch (Exception)
        {
            Console.WriteLine("Expression is invalid: '" + expression + "'");
        }
    }
    public static int EvaluateExpression(string expression)
    {
        string code = string.Format("public static class Func{{ public static int func(){{ return {0};}}}}", expression);
        CompilerResults compilerResults = CompileScript(code);
        if (compilerResults.Errors.HasErrors)
        {
            throw new InvalidOperationException("Expression has a syntax error.");
        }
        Assembly assembly = compilerResults.CompiledAssembly;
        MethodInfo method = assembly.GetType("Func").GetMethod("func");
        return (int)method.Invoke(null, null);
    }

    public static CompilerResults CompileScript(string source)
    {

        CompilerParameters parms = new CompilerParameters();
        parms.GenerateExecutable = false;
        parms.GenerateInMemory = true;
        parms.IncludeDebugInformation = false;
        CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");
        return compiler.CompileAssemblyFromSource(parms, source);
    }

推荐答案

该代码不会在任何地方保存.cs文件。它为内存中的代码创建文本,在内存中编译它,并返回生成的程序集。它无法保存任何地方。返回程序集后,源代码超出范围并被销毁。



那么,问题是什么?虽然有效,但它是评估表达式的一种相当低效的方法。还有其他更快,更灵活的评估表达式的方法,如果这是你正在尝试做的事情。
That codes doesn't save a .cs file anywhere. It creates the text for the code in-memory, compiles it in-memory, and returns the resulting assembly. It doesn't save anything anywhere. Once the assembly is returned, the source code goes out of scope and is destroyed.

So, what's the problem? Though effective, it's a rather inefficient way of evaluating expressions. There are other faster, and more flexible, ways of evaluating expressions if that's what you're trying to do.


它不会保存在任何地方,类在内存中创建,所以当你的进程结束了类也被破坏了。
It doesn't save anywhere, the class is created in memory so when your process ends the class is destroyed too.


正如其他人所说的那样,有更好的方法可以做到这一点。请参见此处:微小的表达评估器 [ ^ ]
As the others have said, there are much better ways to do that. See here for example: A Tiny Expression Evaluator[^]


这篇关于如何使用C#在.NET中运行时创建CLASS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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