简体   繁体   English

C#运算符作为函数

[英]C# operators as functions

Is there a way to use operators as functions without declaring them manually? 有没有办法将运算符用作函数而无需手动声明它们?

Func<bool, bool> not = x => !x;

Similar to (+) / (-) in Haskell. 类似于Haskell中的(+) / (-) Would be handy in various LINQ scenarios involving conditional query construction. 在涉及条件查询构造的各种LINQ场景中会很方便。 Maybe some C# (4.0+) trick I don't know about. 也许一些我不知道的C#(4.0+)技巧。

Edit: here is a sample to clarify what I mean: 编辑:这是一个澄清我的意思的样本:

 int MyWhere(Func<bool, bool, bool> cond) {}

a usual call would be: 通常的电话会是:

MyWhere((x,y) => x && y)

a cool call would be (assuming Haskell style): 一个很酷的电话会是(假设Haskell风格):

MyWhere((&&))

No. 没有。

You can find the definitions (F12 in VS) for the operators you can overload, and there exists a 你可以找到你可以重载的运算符的定义(VS中的F12),并且存在一个

 // struct Double
 public static bool operator ==(double left, double right);

But there is no way to call Double.operator==(a, b) . 但是没有办法调用Double.operator==(a, b)

The Framework does offer a a.Equals(b) for this particualr case, but there is no a.Add(b) . 该框架确实a.Equals(b)情况提供了a.Equals(b) ,但没有a.Add(b)

For documentary purposes: user-defined operator are functions, however the C# language explicitly prohibits explicit calls (don't know the rationale). 出于纪录目的:用户定义的运算符是函数,但是C#语言明确禁止显式调用(不知道基本原理)。 Eg: 例如:

public class X
{
    public static X operator+(X a, X b)
    {
        return new X();
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var q = new X() + new X();
        X.op_Addition(q,q); // error CS0571: 
        //   `Program.X.operator +(Program.X, Program.X)': cannot explicitly
        //   call operator or accessor
    }
}

If you were writing IL, you'd write this: 如果您正在编写IL,那么您可以这样写:

newobj instance void class X::'.ctor'()
newobj instance void class X::'.ctor'()
call class X class X::op_Addition(class X, class X)
stloc.0 

If i understand what you are want to do right, you can use System.Reflection and Delegate.CreateDelegate to create a delegate to the operator method. 如果我理解你想做什么,你可以使用System.ReflectionDelegate.CreateDelegate来创建一个操作符方法的委托。

Of course i never testet it, but operator methods are methods so it should work. 当然我从不测试它,但操作符方法是方法所以它应该工作。 This could also be automated ( To save time compared to the straight forward method ). 这也可以自动化(与直接方法相比节省时间)。

See: 看到:

http://msdn.microsoft.com/de-de/library/53cz7sc6.aspx http://msdn.microsoft.com/de-de/library/53cz7sc6.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM