为什么我们需要方法重载 [英] Why we need method overloading

查看:153
本文介绍了为什么我们需要方法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

we can use same method name with different parameters and different return type in method overloading.

in-spite of doing it, we can have totally different method to call..

then why exactly we use overloading concept..??

I need a perfect, to the point answer as I am not aware of this.
Please don't reply explaining what method overloading is





我有什么尝试过:





What I have tried:

in-spite of doing it, we can have totally different method to call..

推荐答案

>我们可以用一种完全不同的方法来调用



这是真的。但是方法重载的优点是,如果函数名与两个实现相关,它可以让我们重用函数名。我们来看看 Convert.ToInt32 [ ^ ]。超载列表有19个项目。您可以使用ToInt32FromString等19个函数替换它,但方法重载允许我们根据传递的内容为ToInt32创建19个实现。这样可以保持简单:只有一个方法名称可以将大量内容转换为Int32。
> we can have a totally different method to call

This is true. But method overloading has the advantage that it can let us 'reuse' function names if the function name is relevant for both implementations. Let's take a look at Convert.ToInt32[^]. The overload list has 19 items. You can replace this by 19 functions like ToInt32FromString, but method overloading allows us to create 19 implementations for ToInt32 depending on what gets passed. This keeps things simple: you only have one method name to convert a lot of stuff to an Int32.


如果要构建一些公共API,则方法重载可能有用的一种情况。例如,ASP.NET MVC使用它来通过HTML帮助程序提供功能,您可以使用不同的参数多次重载相同的方法。
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.


要了解过载优势,请查看 OpenGL 4参考页 [ ^ ](过载不可用)。
To get an idea of overload advantages, have a look at OpenGL 4 Reference Pages[^] (overload unavailable there).


这篇关于为什么我们需要方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆