我目前正在生成代码,以便可以使等效于动态代理(调用方法时没有反射的开销),像这样:
//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中也可能不起作用。还有其他选择吗?