2016-01-19 19 views
1

我需要定义的方法,它获取参数两个委托,并返回委托(这将乘以paramiters这个委托的返回)。现在我有这样的,但我不能使它可编译。你能提供一些建议,还是回答?我将非常感激。方法返回委托,它是来自参数值代表的乘法值

public Delegate MathP(Delegate mydelegate, Delegate mydelegate2) 
    { 

     return (Delegate) Delegate.CreateDelegate Delegate (int x, int y) { 
       int results = (int)mydelegate.DynamicInvoke(x, y); 
       int results2 = (int)mydelegate2.DynamicInvoke(x, y); 

       return results* results2; 
      }; 
    } 
+0

你能说出所有委托实例符合Func 签名? – galenus

+0

@galenus是的,它们都符合Func 签名。 – Yurrili

回答

2

你可能最好使用表达式树。 这种方法会产生你所期望的结果:

static Delegate Combine(Delegate first, Delegate second) 
{ 
    var firstParam = Expression.Parameter(typeof(int)); 
    var secondParam = Expression.Parameter(typeof(int)); 

    var expression = Expression.Lambda<Func<int, int, int>>(
     Expression.Multiply(
      Expression.Call(first.GetMethodInfo(), firstParam, secondParam), 
      Expression.Call(second.GetMethodInfo(), firstParam, secondParam)), 
     firstParam, 
     secondParam); 

    return expression.Compile(); 
} 

此外,您可以更换DelegateFunc<int,int,int>方法签名所以结果的调用将是Combine方法本身的速度和调用 - 类型安全。

但请记住,以这种方式获得的代表最好能被缓存,否则编译lambda的开销会很大。

另一种方法,简单的和不太高性能之一是:

static Delegate CombineSimple(Delegate first, Delegate second) 
{ 
    return new Func<int, int, int>(
     (firstParam, secondParam) => 
      (int)first.DynamicInvoke(firstParam, secondParam) * 
      (int)second.DynamicInvoke(firstParam, secondParam)); 
} 
3

如果你可以重写你的与会代表Func的,这是相当容易做到:

public Func<int, int, int> MathP 
    (Func<int, int, int> mydelegate 
    , Func<int, int, int> mydelegate2 
    ) 
{ 
    return new Func<int, int, int> 
     ((x, y) => mydelegate(x, y) * mydelegate2(x, y) 
     ); 
}