gpt4 book ai didi

c# - 动态使用运行时编译的程序集

转载 作者:太空狗 更新时间:2023-10-30 00:53:18 27 4
gpt4 key购买 nike

我从代码动态编译代码:

            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)。 (我可以用反射调用,我知道,我只是在寻找另一种方法,因为我们需要测试动态代码)

最佳答案

您不能在这种情况下直接使用dynamicdynamic 总是需要一个类实例,但您试图调用静态类中的方法,因此您没有类实例。

但是,您可以创建一个辅助类并将其与 dynamic 结合使用:

public class StaticMethodInvoker : DynamicObject
{
Type _containingType;

public StaticMethodInvoker(Type containingType)
{
_containingType = containingType;
}

public override bool TryInvokeMember(
InvokeMemberBinder binder, Object[] args, out Object result)
{
result = _containingType.InvokeMember
binder.Name,
BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.Public,
null, null, args);
return true;
}
}

用法:

var type = results.CompiledAssembly.GetType("CodeInjection.DynConcatenateString");
dynamic DynConcatenateString = new StaticMethodInvoker(type);
string result = DynConcatenateString.Concatenate(s1, s2);

关于c# - 动态使用运行时编译的程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16918612/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com