1

在调用创建编译表达式时,我试图在生成的编译委托上调用 CreateDelegate,但遇到 NotSupportedException,解释是:派生类必须提供实现。如何为已编译的方法创建委托?

public delegate int AddOne(int input);

void Main()
{
    var input = Expression.Parameter(typeof(int));
    var add = Expression.Add(input,Expression.Constant(1));
    var lambda = Expression.Lambda(typeof(AddOne),add,input);
    var compiled = (AddOne)lambda.Compile();
    compiled.Method.CreateDelegate(typeof(AddOne));
}
4

1 回答 1

3

You don't need to call CreateDelegate. Casting the result from lambda.Compile to AddOne was all you needed.

Observe:

public delegate int AddOne(int input);

public int Test(AddOne f)
{
   return f(1);
}

void Main()
{
    var input = Expression.Parameter(typeof(int));
    var add = Expression.Add(input,Expression.Constant(1));
    var lambda = Expression.Lambda(typeof(AddOne),add,input);
    var compiled = (AddOne)lambda.Compile();
    Console.WriteLine(Test(compiled)); // 2
}

You can successfully call the Test method, which accepts a delegate of type AddOne.

于 2013-09-26T19:41:37.080 回答