如何在运行时动态创建一个 C# 类(根据现有类)?

5

背景:

我们有一个涉及客户端(Javascript)和服务器端(C#)的项目。由于需要在两个端上运行计算逻辑,所以代码被写成了Javascript和C#两种语言的形式。 我们已经为C#版本的类编写了许多单元测试。我们的目标是分享这些单元测试,使得Javascript版本也能够通过测试。

当前情况:

我们可以在一个嵌入式JS引擎(Microsoft ClearScript)中运行Javascript代码。代码如下:

public decimal Calulate(decimal x, decimal y) 
{
     string script = @"
            var calc = new Com.Example.FormCalculater();
            var result = calc.Calculate({0}, {1});";

     this.ScriptEngine.Evaluate(string.Format(script, x, y));

     var result = this.ScriptEngine.Evaluate("result");
     return Convert.ToDecimal(result);
}

然而,编写这样的类需要很多工作。我们正在寻找一种在运行时动态创建此类的方法。

例如,我们有一个C#类(在JS文件中也有其JS版本):

public class Calculator {
    public decimal Add(decimal x, decimal y){ ... }
    public decimal Substract(decimal x, decimal y){ ... }
    public decimal Multiply(decimal x, decimal y){ ... }
    public decimal Divide(decimal x, decimal y){ ... }
}

我们希望创建一个动态类,该类具有相同的方法,但调用脚本引擎来调用相关的JS代码。
这是否可能实现?

CodeDom可能是你正在寻找的。https://msdn.microsoft.com/zh-cn/library/y2k85ax6(v=vs.110).aspx - HungDL
3个回答

5

听起来很简单。现在你甚至不需要手动发出任何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);

为了完整起见,这里是我使用的 IYourInterfaceYourClassBase

public interface IYourInterface
{
  decimal Add(decimal x, decimal y);
}

public abstract class YourClassBase
{
  public ScriptEngine ScriptEngine { get; set; }
}

如果可以的话,我强烈建议使用文本模板来在编译时生成源代码。动态代码往往很难调试(当然,编写也是)。另一方面,如果您只是从模板生成这些内容,您将在代码中看到整个生成的帮助类。


1

你的链接非常有帮助。谢谢! - Zach

0

你可以使用C#的dynamic来共享单元测试代码。假设你有一个C#类:

public class Calculator {
    public decimal Add(decimal x, decimal y) { return x + y; }
}

假设您还创建了一个实现相同接口的JavaScript对象:

scriptEngine.Execute(@"
    calculator = {
        Add: function (x, y) { return x + y; }
    };
");

你可以为两者创建一个测试方法:

public static void TestAdd(dynamic calculator) {
    Assert.AreEqual(3, calculator.Add(1, 2));
}

以下是如何测试这两种实现的方法:

TestAdd(new Calculator());
TestAdd(scriptEngine.Script.calculator);

这个好处在于你不需要为每个测试调用解析和编译新的脚本代码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接