2

我有一个string input;带有一些代码的字符串(以下所有内容都在该字符串中)

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

现在,我想实现以下场景:

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

我假设实际的 T1、TResult 是已知的(这里:字符串、字符串),并且该输入被命名为“s”。我可以这样实现:

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()));
}

但这是相当复杂的方式。如果我知道我只想要一个Func<T1, TResult>,而不是整个编译的程序集,实例化类(或调用一个静态方法),有什么方法可以简化这一点?

当然,我可以使用这段代码,并把它打扮得很好——将它包装在一个泛型类中,获取 T1、TResult 类型名称以放入TempClass模板(String.Format("public {0} temp_func({1} s)",typeof(TResult).Name, typeof(T1).Name);)中,但它有一种润滑方形轮轴的感觉骑行更顺畅...

4

1 回答 1

1

我选择了这样的东西:

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;
    }
}

那么使用就相当简单了:

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]
于 2015-01-30T10:51:04.450 回答