开发者

C# Operator overloading - towards practical

Most of the websites,articles i have gone through explains operator overloading by giving the following standard example.

class Complex
    {
        int real;
        int imaginary;

        public Complex(int real, int imaginary)
        {
            this.real = real;
            this.imaginary = imaginary;
        }

        public static Complex operator +(Complex com1, Complex com2)
        {
            return new Complex(com1.real + com2.real, 
           开发者_开发技巧         com1.imaginary + com2.imaginary);
        }

        public override string ToString()
        {
            return (String.Format("{0} + {1}i", real, imaginary));
        }
}

}   

We as beginners think ,operator overloading would be quite useful for scientific-application.

Will operator overloading be quite useful for e-commerce ,ebanking or other applications? As we saw standard example given above,it quite hard to grasp the real power of operator overloading.could you please explain it by providing example as necessary.


In the applications you mentioned, addition and subtraction (and other needed math) are commonly used, standardized operations, so overloading is not required.

For all other operations, I prefer using methods.

The scientific example is useful for operator overloading because it redefines math operations in terms of a data type that is not known by the system. If you wanted to create a custom object that semantically could be added or subtracted by another custom object instance, then operator overloading might be appropriate.

But caution is advised. The overload must make conceptual sense to other programmers. To provide a trivially absurd example, it is perfectly feasible (but not at all acceptable) to define addition as subtraction.


Just an example of the operator overloading from the .NET Framework

Console.WriteLine(DateTime.Now + TimeSpan.FromDays(1));

As you can see, it's not "scientific". Let's put it like this. If you operate with data structures, where it is a common knowledge of what subtraction, addition, or logical operation should do, then use an operator overload. If you invent your own structures and rules, you better use methods. The rule is that the use of the overloaded operator should feel really natural not just to you, but to other developers reading your code.


Ok, here's an example. I have an application, where many of the domain objects include an attribute which specifies a "Calendar Month", where the specific day of the month is irelevant. (Dec 1998, Mar 2003, etc.)

So, I have created a struct that represents these values internally as a primitive integer, (number of months since Jan 2000 I think). This struct includes numerous methods to instaniate instances of this CalendarMonth struct from various input types (DateTimes, strings that can be converted into a date time or a datetime wothout the year, etc. The struct has a CalendarMonth Parse(string inputValue) and a bool TryParse(string inputValue out CalendarMonth calMonth) methods, as these bits of functionality are used all over this application.

This struct also encapsulates methods that return dateTime values for the first Of the Month, the lastday of the month, the start of the month UTC, etc. etc.

It also has numerous operator overloads, so that I can 'add/subtract' a timespan to a calendar month and get a CalendarMonth, or Subtract two CalendarMonth structs to get a TimeSpan... kinda like datetimes do. It also has both implicit and explicit cast operator overlaods to cast back and forth between datetimes and CalendarMonth structs...

I'd say, in general, this technique is useful anytime you have a Type in your Domain that could be called a value-type (in that it has no "identity", but it defined simply by it's attribute values, and which has quantitative behavior qualities within the problem domain your application lives in.


@ Robert agreed. If you need to modify an operator just write a function or 'method'. Operator overloading, in my humble opinion is not only not necessary it makes your code nigh unreadable


Please do not abuse operator overloading, if you can help it in any way. The problem is with code readability - it is easy to get confused when you see:

CustomerCart cart = new CustomerCart();
IList<Purchases> purchases = this.GetPurchases();

and later on down in the code:

bool success = cart + purchases;

This would certainly make me do a double-take. With more "primitive" types that you come up with, such as Complex, you can get away with this, but generally with high-level types you want to avoid operating overloading since it obfuscates the code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜