开发者

Operator Overloading in C# - Where should the actual code code go?

A bit of a conceptual question:

I'm creating my custom structure, in the vein of a Vector3 (3 int values) and I was working through overloading the standard operators (+,-,*, /, == etc...)

As I'm building a library for external use, I'm attempting to conf开发者_运维知识库orm to FxCop rules. As such, they recommend having methods that perform the same function.

Eg. .Add(), .Subtract(), etc...

To save on code duplication, one of these methods (the operator overload, or the actual method) is going to call the other one.

My question is, which should call which?

Is it (and this is only an example code):

A)

    public static MyStruct operator +(MyStruct struc1, MyStruct struct2)
    {
        return struc1.Add(struct2);
    }

    public MyStruct Add(MyStruct other)
    {
        return new MyStruct (
            this.X + other.X,
            this.Y + other.Y,
            this.Z + other.Z);
    }

or:

B)

    public static MyStruct operator +(MyStruct struc1, MyStruct struct2)
    {
        return new MyStruct (
            struct1.X + struct2.X,
            struct1.Y + struct2.Y,
            struct1.Z + struct2.Z);
    }

    public MyStruct Add(MyStruct other)
    {
        return this + other;
    }

I'm really not sure either is preferable, but I'm looking for some opinions :)


I would go with A). Since operator overloading is not CLS compliant (not all .NET languages support overloading operators) it can be considered as syntactical sugar around the actual Add method.


Either. It really doesn't matter. I'd expect the code to be inlined anyway, so go with whatever you consider more readable.


Definitely A.

Methods are the real thing. Method can get extra params, they can be marked as virtual ( => can be override), overloaded, and are generally more the nature of the language. Before looking for practical reason, i think you need to feel it. beside, the CIL language protocol is not binding to support operator overloading, and that sort of clear victory to the method.


Since it is a struct, inheritance isn't an issue (otherwise "A" makes virtual easier) - so I would go with "B", simply because I expect to call + more than I call Add... less indirection.

For a class with a genuine need for + and inheritance (unlikely), I would go "A".


I would vote for option B since that's the more intuitive place to look at when looking at what values/properties are actually being used in the operator.


I would also go with A for many of the reasons stated above, in particular because I view the operator overloading as a syntax mechanism that is wrapping the actual method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜