开发者

When should I Use Method Overloading in real world Projects? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonab开发者_StackOverflow中文版ly answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

When Should i Use Method overloading in real time development,please suggest some links.


Method overloading is an OOP technique used for class design. It has nothing to do with real time development.

If you are asking about real world uses of method overloading - it is a useful technique and you can see it being used all over the BCL.

Examples are some of the Linq extension methods, where many of the extension methods have multiple overloads (see IEnumerable<T>).

Method overloads are best used when the same operation can be done in several different ways, depending on parameters - for example sorting. An overload with no parameters may apply a default sort. An overload with a sort order will allow sort order, and another one may have a Func delegate that determines the sort algorithm.


Overloading is used (recommended) when multiple methods have the same purpose but there is more than one way to start it.

So we rather have

int Add(int a, int b) { ...}
int Add(int a, int b, int c) { ... }

than

int Add2(int a, int b) { ...}
int Add3(int a, int b, int c) { ... }

or

int Add(int a, int b, int? c) { ...}

The last example could also be done using (C#4) optional parameters.

Another good candidate for overloading:

void ReadXml(string fileName) { ... }
void ReadXml(Stream strm) { .... }


Well now with things like initializers and named parameters in c# it really doesn't seem as necessary.


One scenario where method overloading could be useful is if you are building some public API. For example ASP.NET MVC use it to provide functionality through HTML helpers where you have the same method overloaded multiple times with different arguments.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜