OR(|), XOR(^), AND(&) overloading [closed]

2019-06-10 16:50发布

问题:

How do I overload the &, | and ^ operators in C# and how does overloading work?

I have been trying to find some good answers for some time but have not found any. I will share any helpful articles.

回答1:

By implementing operators for your classes in C#, you are not actually overloading operators. You are simply implementing them for the first time. They are methods, just like any other, but with special syntax. Instead of calling c = Add(a, b) you call c = a + b, where + is an operator (method) that returns a value.

By implementing the following methods, the &= |=, and ^= methods have been automatically implemented.

public class MyClass
{
    public static MyClass operator &(MyClass left, MyClass right)
    {
        return new MyClass();
    }

    public static MyClass operator |(MyClass left, MyClass right)
    {
        return new MyClass();
    }

    public static MyClass operator ^(MyClass left, MyClass right)
    {
        return new MyClass();
    }
}

var a = new MyClass();
var b = new MyClass();

var c = a & b;
var d = a | b;
var e = a ^ b;

a &= b; // a = a & b;
c |= d; // c = c & d;
e ^= e; // e = e ^ e;

Overloading is performed at compile time. It ensures that a specific method is called based on the method's name and parameter type and count.

Overiding is performed at runtime. It allows a subclass's method to be called instead of the parent method, even when the instance was being treated as the parent class.



回答2:

For some articles/tutorials/references on operator overloading including binary/bitwise operators and sample source code see:

  • http://www.codeproject.com/KB/cs/introtooperatoroverloads.aspx
  • http://www.dotnetperls.com/operator
  • http://msdn.microsoft.com/en-us/library/aa691324%28v=vs.71%29.aspx
  • http://msdn.microsoft.com/en-us/library/aa288467%28v=vs.71%29.aspx

As for "how to use them" the basic rule is that overloaded operators should make sense in the domain you implement them...

For example you could build a genetic/evolutionary algorithm and define some/all of the bitwise/binary operators in a way consistent with the "recombination/mutation" step (i.e. creating the next generation from current population) of that algorithm - this would make for rather elegant code in that specific context.



回答3:

How to use them? Carefully. They need to make sense. E.g. Defining say a Type to hold a ComplexNumber or a Matrix and then overloading arithmetical operators makes sense.

Don't go down the foolish route of overloading an operator because you don't like typing.

e.g. MyThingyList + SomeFileName loads MyThingyList from the file.

or

MyThingyList-- calls MyThingsList.Clear().