Overloading operator for generics C# [duplicate]

谁都会走 提交于 2021-02-08 16:55:20

问题


I would like to create a procedure class that supports connecting to another procedure like so: a|b|c|d (this should result a procedure takes a's input type, and give d's output type)

class Procedure<I,O>
{
  public Func<I,O> func;
  public Procedure(Func<I, O> func)
  { this.func = func; }
  public static Procedure<I, O> operator| (Procedure<I, M> proc1, Procedure<M, O> proc2)
  { return new Procedure<I,O>((x) => proc2.Process(proc1.Process(x))); }
  public O Process(I input)
  { return func.Invoke(input); }
}

The compiler complains it can't find M. Normally I would add after the method name, however in this case it gets recognized as part of the operator name. What do?

Just a side note, I'm trying to move my Scala lib into C# here.


回答1:


The rules of overriding a binary operation are that one of the two parameters must be the same type as the enclosing class. So either proc1 or proc2 must be of type Procedure< I,O>. This precludes it being able to achieve what you need.

I can see what you are trying to do but it cannot be done in C#. The compiler will generate just a single operator override implementation for each class that is generated from the unique generic parameters. In your case you would need the compiler to automatically generic as many as are needed to handle all the intermediate types used.




回答2:


You can't do this because M is not a type parameter of Procedure class and you cannot define it for operator | - it's C# limitation. To tackle this use a method, not operator:

public static Procedure<I, O> Composition<M>(Procedure<I, M> proc1, Procedure<M, O> proc2)
    {
        return new Procedure<I, O>((x) => proc2.Process(proc1.Process(x)));
    }


来源:https://stackoverflow.com/questions/29158535/overloading-operator-for-generics-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!