使用CSharpCodeProvider(System.CodeDom)进行的动态代码编译是否可以在.Net Core 2.x中使用?

时间:2019-05-21 22:21:40

标签: .net .net-core .net-4.5 codedom .net-core-2.2

我目前正在生成代码,以便可以使等效于动态代理(调用方法时没有反射的开销),像这样:

//This is not how I'd actually use it, but shows the code generation
public string GetSomethingWrapped(object target)
{
    //Generate the code
    string code = CreateCode(target.GetType());

    CSharpCodeProvider provider = new CSharpCodeProvider();

    //We want this to be in-memory only
    CompilerParameters parameters = new CompilerParameters
    {
        GenerateExecutable = false,
        GenerateInMemory = true,
        OutputAssembly = Path.GetTempFileName()
    };

    //It needs to reference our running project's classes/namespaces
    parameters.ReferencedAssemblies.Add(typeof(MyClass).Assembly.Location);

    //Compile the code
    CompilerResults results = provider.CompileAssemblyFromSource(
        parameters,
        code
    );

    //...elided...
    IMyTestType instance = (IMyTestType) results.CompiledAssembly.CreateInstance(
        NAMESPACE + "MyTestTypeImpl",
        false,
        BindingFlags.Instance | BindingFlags.Public,
        (Binder)null,
        new object[] { myBaseObject },
        (CultureInfo)null,
        (object[])null
    );

    //Now I can call methods directly on it
    return instance.GetSomething();
}

我已经做了一些研究,似乎即使在包含System.CodeDom的情况下,这在.Net Core 2.x中也可能不起作用。还有其他选择吗?

0 个答案:

没有答案