简体   繁体   English

为什么 C# 运算符重载必须是静态的?

[英]Why must C# operator overloads be static?

Why does C# require operator overloads to be static methods rather than member functions (like C++)?为什么 C# 要求运算符重载是静态方法而不是成员函数(如 C++)? (Perhaps more specifically: what was the design motivation for this decision?) (也许更具体地说:这个决定的设计动机是什么?)

This has been answered in excruciating detail by Eric Lippert in a blog post that has since been removed. Eric Lippert 在一篇博客文章中详细回答了这个问题,该文章已被删除。 Here is the archived version .这是存档版本

There is also another subtler point about value types and instance operators.关于值类型和实例运算符还有另一个更微妙的地方。 Static operators make this kind of code possible:静态运算符使这种代码成为可能:

class Blah {

    int m_iVal;

    public static Blah operator+ (Blah l, int intVal)
    {
        if(l == null)
            l = new Blah();
        l.m_iVal += intVal;
        return l;
    }
}

//main
Blah b = null;
b = b + 5;

So you can invoke the operator, even though the reference is null.因此,即使引用为空,您也可以调用运算符。 This wouldn't be the case for instance operators.对于实例运算符,情况并非如此。

Take a look at this post .看看这个帖子

A couple of reasons, the primary seeming to be to preserve operator symmetry (such that the left hand side of a binary operation does not get special treatment, as being responsible for dispatching the operation).有几个原因,主要似乎是为了保持运算符的对称性(例如二元运算的左侧没有得到特殊处理,因为它负责调度运算)。

Perhaps its best to think why should the methods not be static.也许最好想想为什么方法不应该是静态的。 There is no need for state and hence this.不需要状态,因此不需要状态。

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

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