泛型C#的重载运算符 [英] Overloading operator for generics C#

查看:92
本文介绍了泛型C#的重载运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个过程类,该类支持连接到另一个过程,例如:a | b | c | d(这将导致过程采用a的输入类型,并赋予d的输出类型)

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); }
}

编译器抱怨找不到M.通常我会在方法名称之后添加,但是在这种情况下,它会被识别为运算符名称的一部分.怎么办?

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?

请注意,我正在尝试将我的Scala库移动到C#中.

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

推荐答案

覆盖二进制运算的规则是,两个参数之一必须与封闭类具有相同的类型.因此proc1或proc2必须是Procedure<I,O>.这使得它无法实现您的需求.

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.

我可以看到您要执行的操作,但是用C#无法完成.对于从唯一的通用参数生成的每个类,编译器将只生成一个运算符覆盖实现.在您的情况下,您将需要编译器自动泛型处理所需的所有中间类型.

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.

这篇关于泛型C#的重载运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆