C# Generic Operators

前端 未结 5 1763
心在旅途
心在旅途 2020-11-27 07:25

I am trying to implement a generic operator like so:

class Foo
{
   public static T operator +(T a, T b) 
   {
       // Do something with a and b t         


        
5条回答
  •  爱一瞬间的悲伤
    2020-11-27 07:36

    https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html

    static T Add(T a, T b) {
        //TODO: re-use delegate!
        // declare the parameters
        ParameterExpression paramA = Expression.Parameter(typeof(T), "a"),
            paramB = Expression.Parameter(typeof(T), "b");
        // add the parameters together
        BinaryExpression body = Expression.Add(paramA, paramB);
        // compile it
        Func add = Expression.Lambda>(body, paramA, paramB).Compile();
        // call it
        return add(a,b);       
    }
    

提交回复
热议问题