我从代码动态编译代码:
string code = @"
namespace CodeInjection
{
public static class DynConcatenateString
{
public static string Concatenate(string s1, string s2){
return s1 + "" ! "" + s2;
}
}
}";
// http://stackoverflow.com/questions/604501/generating-dll-assembly-dynamically-at-run-time
Console.WriteLine("Now doing some injection...");
Console.WriteLine("Creating injected code in memory");
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
//parameters.OutputAssembly = "DynamicCode.dll"; // if specified creates the DLL
CompilerResults results = icc.CompileAssemblyFromSource(parameters, code);
然后我可以通过反射调用该方法:
Console.WriteLine("Input two strings, and I will concate them with reflection:");
var s1 = Console.ReadLine();
var s2 = Console.ReadLine();
var result = (string)results.CompiledAssembly.GetType("CodeInjection.DynConcatenateString").GetMethod("Concatenate").Invoke(null, new object[] { s1, s2 });
Console.WriteLine();
Console.WriteLine("Result:");
Console.WriteLine(result);
但我想调用这样的东西:
Console.WriteLine("Input two strings, and I will concate them with dynamic type:");
var s1 = Console.ReadLine();
var s2 = Console.ReadLine();
dynamic type = results.CompiledAssembly.GetType("CodeInjection.DynConcatenateString");
var resultA = (string)type.Concatenate(s1, s2); // runtime error
// OR
var resultB = (string)CodeInjection.DynConcatenateString.Concatenate(s1, s2); // compile error (cannot find assembly)
Console.WriteLine();
Console.WriteLine("Result:");
Console.WriteLine(resultA);
Console.WriteLine(resultB);
结果B会更好。任何想法如何做到这一点?我需要严格的 .NET 4.0,我们还没有更新到 4.5(因为团队的一半使用 VS 2010)。(我可以用反射调用,我知道,我只是在寻找另一种方式,因为我们需要测试 dyn.code)