Compile Func<T1, TResult> from string on the fly

天涯浪子 提交于 2020-01-04 16:24:51

问题


I have a string string input; with some code (all below is in that string)

var x = s.IndexOf("a");
return String.Format(s, x);

Now, I would like to achieve following scenario:

Func<string, string> f = Compile(input);
var test = "dcba - {0}";
var result = f(test);
// result = "dcba - 3";

I assume, that the actual T1, TResult are known (here: string, string), and that input is named "s". I can achieve it this way:

var input = "var x = s.IndexOf(\"a\"); return String.Format(s, x);";
var containerClass = @"using System; class TempClass {{ public string temp_func(string s){{ {0} }} }}";
var code = String.Format(containerClass, input);

// Create a new instance of the C# compiler
var compiler = new CSharpCodeProvider();



var params = new CompilerParameters
{
    GenerateExecutable = false,
    GenerateInMemory = true
};
params.ReferencedAssemblies.Add("System.dll");
var results = compiler.CompileAssemblyFromSource(params, code);

Func<string, string> f;
if (results.Errors.Count == 0)
{
    f = s =>
    {
        var myClass = results.CompiledAssembly.CreateInstance("TempClass");
        return (string) myClass.GetType().
            GetMethod("temp_func").
            Invoke(myClass, new object[] {s});
    };

    // test:
    Console.WriteLine(f(Console.ReadLine()));
}

But it is fairly complicated way. Is there any way to simplify this, if I know that I just want a Func<T1, TResult>, not a whole compiled assembly, instancing classes (or calling a static method on one)?

I can take this code, of course, and dress it nicely - wrap it in a generic class, get T1, TResult type names to put into the TempClass template (String.Format("public {0} temp_func({1} s)",typeof(TResult).Name, typeof(T1).Name);), but it has a feel of greasing an axle of a square wheel to make ride smoother...


回答1:


I went with something like this:

public class DynamicFunction
{
    private static int _counter = 0;
    private const string ClassBody = "{2} public static class DynamicFunctionHost{0} {{ {1} }}";
    private const string ClassName = "DynamicFunctionHost{0}";
    private const string FunctionName = "func";
    private const string T1FuncBody = "public static {1} func({0} param1){{ {2} }}";

    public static Func<T1, TResult> Get<T1, TResult>(string funcBody, string[] referenced, string[] usingNs)
    {
        var code = String.Format(ClassBody, _counter,
            String.Format(T1FuncBody, typeof (T1).Name, typeof (TResult).Name, funcBody),
            String.Join("\n", usingNs.Select(r => String.Format("using {0};", r))));
        var result = Compile(code, referenced);
        var host =
            result.CompiledAssembly.DefinedTypes.Single(
                typeinfo => typeinfo.FullName.Equals(String.Format(ClassName, _counter)));

        ++_counter;
        return input => (TResult) host.GetMethod(FunctionName).Invoke(null, new object[] { input });
    }

    private static CompilerResults Compile(string code, string[] referenced)
    {
        var compiler = new CSharpCodeProvider();
        var parameters = new CompilerParameters
        {
            GenerateExecutable = false,
            GenerateInMemory = true
        };
        foreach (var r in referenced)
            parameters.ReferencedAssemblies.Add(r);

        var results = compiler.CompileAssemblyFromSource(parameters, code);
        if (results.Errors.Count == 0) return results;

        // else
        var e = new ArgumentException("Errors during compilation", "code");
        e.Data.Add("Errors", results.Errors);
        throw e;
    }
}

The use is fairly simple then:

var f = DynamicFunction.Get<string, string[]>("return param1.ToCharArray()", new []{"System.dll","System.Core.dll"}, new []{"System"});
var x = f("abcd"); // =[a,b,c,d]


来源:https://stackoverflow.com/questions/28226271/compile-funct1-tresult-from-string-on-the-fly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!