听起来很简单。现在你甚至不需要手动发出任何IL :)
最简单的方法是忽略“动态创建”部分。您可以使用T4模板,在编译时自动创建类。如果您唯一的考虑因素是单元测试,这是解决问题的一种非常简单的方法。
现在,如果您想真正动态创建类型(在运行时),这将变得有些复杂。
首先,创建一个包含所有所需方法的接口。 C#类将直接实现此接口,而我们将生成帮助器类以符合此接口。
接下来,我们创建帮助器类:
var assemblyName = new AssemblyName("MyDynamicAssembly");
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("Module");
var typeBuilder = moduleBuilder.DefineType("MyNewType", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes, typeof(YourClassBase), new[] { typeof(IYourInterface) } );
TypeBuilder
允许我们定义所有这些方法,下一步让我们来完成这个任务。
// Get all the methods in the interface
foreach (var method in typeof(IYourInterface).GetMethods())
{
var parameters = method.GetParameters().Select(i => i.ParameterType).ToArray();
// We can only compile lambda expressions into a static method, so we'll have this helper. this is going to be YourClassBase.
var helperMethod = typeBuilder.DefineMethod
(
"s:" + method.Name,
MethodAttributes.Private | MethodAttributes.Static,
method.ReturnType,
new [] { method.DeclaringType }.Union(parameters).ToArray()
);
// The actual instance method
var newMethod =
typeBuilder.DefineMethod
(
method.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
method.ReturnType,
parameters
);
// Compile the static helper method
Build(method).CompileToMethod(helperMethod);
// We still need raw IL to call the helper method
var ilGenerator = newMethod.GetILGenerator();
// First argument is (YourClassBase)this, then we emit all the other arguments.
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Castclass, typeof(YourClassBase));
for (var i = 0; i < parameters.Length; i++) ilGenerator.Emit(OpCodes.Ldarg, i + 1);
ilGenerator.Emit(OpCodes.Call, helperMethod);
ilGenerator.Emit(OpCodes.Ret);
// "This method is an implementation of the given IYourInterface method."
typeBuilder.DefineMethodOverride(newMethod, method);
}
为了创建辅助方法体,我使用了以下两个辅助方法:
LambdaExpression Build(MethodInfo methodInfo)
{
// This + all the method parameters.
var parameters =
new [] { Expression.Parameter(typeof(YourClassBase)) }
.Union(methodInfo.GetParameters().Select(i => Expression.Parameter(i.ParameterType)))
.ToArray();
return
Expression.Lambda
(
Expression.Call
(
((Func<MethodInfo, YourClassBase, object[], object>)InvokeInternal).Method,
Expression.Constant(methodInfo, typeof(MethodInfo)),
parameters[0],
Expression.NewArrayInit(typeof(object), parameters.Skip(1).Select(i => Expression.Convert(i, typeof(object))).ToArray())
),
parameters
);
}
public static object InvokeInternal(MethodInfo method, YourClassBase @this, object[] arguments)
{
var script = @"
var calc = new Com.Example.FormCalculater();
var result = calc.{0}({1});";
script = string.Format(script, method.Name, string.Join(", ", arguments.Select(i => Convert.ToString(i))));
@this.ScriptEngine.Evaluate(script);
return (object)Convert.ChangeType(@this.ScriptEngine.Evaluate("result"), method.ReturnType);
}
如果您希望的话,可以将其变得更加具体(生成表达式树以更好地匹配给定方法),但这样做会给我们带来很多麻烦,并且允许我们在大部分复杂的任务上使用C#。
我假设所有的方法都有返回值。如果没有,您需要进行调整。
最后:
var resultingType = typeBuilder.CreateType();
var instance = (IYourInterface)Activator.CreateInstance(resultingType);
var init = (YourClassBase)instance;
init.ScriptEngine = new ScriptEngine();
var result = instance.Add(12, 30);
Assert.AreEqual(42M, result);
为了完整起见,这里是我使用的 IYourInterface
和 YourClassBase
:
public interface IYourInterface
{
decimal Add(decimal x, decimal y);
}
public abstract class YourClassBase
{
public ScriptEngine ScriptEngine { get; set; }
}
如果可以的话,我强烈建议使用文本模板来在编译时生成源代码。动态代码往往很难调试(当然,编写也是)。另一方面,如果您只是从模板生成这些内容,您将在代码中看到整个生成的帮助类。