0

我正在编写管道逻辑。这个想法是在对象的实例中动态创建并在每种情况下执行方法 Run 方法。我可以很容易地用反射 Activator.CreateInstance 做旧方法,但在这种情况下性能很重要。

我看了很多代码示例和教程,我认为我正确地使用了 Lambda 表达式。我只能弄清楚调用部分。提前致谢。

namespace Pipelines
{
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

public interface IProcessor
{
    string Name { get; set; }
}

public interface IAspNetMembershipId : IProcessor
{
    Guid? Id { get; set; }
}

public class ProcessorOne
{
    public void Run(IProcessor args)
    {
        /* Do Something */
    }
}

public class ProcessorTwo
{
    public void Run(IAspNetMembershipId args)
    {
        /* Do Something */
    }
}

public class Program
{
    static void Main(string[] args)
    {
        var arguments = new AspNetMembershipId() { Name = "jim" };

        /* Pipeline1 Begin */
        Type type = typeof(ProcessorOne);
        NewExpression newExp = Expression.New(type);

        var p1 = Expression.Parameter(newExp.Type, "ProcessorOne");
        var p2 = Expression.Parameter(typeof(IProcessor), "args");

        MethodInfo methodInfo = (from method in newExp.Type.GetMethods() where method.Name.StartsWith("Run") select method).First();
        var invokeExpression = Expression.Call(p1, methodInfo, p2);

        Delegate func = Expression.Lambda(invokeExpression, p1, p2).Compile();

        /* Throws an exception. This not correct! */
        func.DynamicInvoke(newExp, arguments);
        /* or */
        func.DynamicInvoke(arguments);

        /* Pipeline2 Begin */
    }
}

}

4

1 回答 1

0

这应该有效:

var arguments = new AspNetMembershipId() { Name = "jim" };

/* Pipeline1 Begin */
Type type = typeof(ProcessorOne);

NewExpression newExp = Expression.New(type);

var p2 = Expression.Parameter(typeof(IProcessor), "args");

MethodInfo methodInfo = (from method in newExp.Type.GetMethods()
                            where method.Name.StartsWith("Run")
                            select method).First();

var invokeExpression = Expression.Call(newExp, methodInfo, p2);
Delegate func = Expression.Lambda(invokeExpression, p2).Compile();

/* Doesn't throw exception any more */
func.DynamicInvoke(arguments);

请注意,我已newExp直接提供给 invokeExpression 并将arguments其作为唯一参数。

于 2011-11-26T18:35:05.923 回答