C#方法的重载
C#方法的重载
方法重载是指在一个类中定义多个同名的方法,但要求每个方法具有不同的参数的类型或参数的个数。调用重载方法时,编译器能通过检查调用的方法的参数类型和个数选择一个恰当的方法。方法重载通常用于创建完成一组任务相似但参数的类型或参数的个数或参数的顺序不同的方法。 方法重载,就是在类中可以创建多个方法,它们可以有相同的名字,但必须具有不同的参数,即或者是参数的个数不同,或者是参数的类型不同。调用方法时通过传递给它们的不同个数和类型的参数,以及传入参数的顺序来决定具体使用哪个方法。
实例:
先在页面拉几个Button
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="没有参数" OnCommand="Button1_Command" />
<asp:Button ID="Button2" runat="server" Text="一个参数" OnCommand="Button2_Command" />
<asp:Button ID="Button3" runat="server" Text="两个参数" OnCommand="Button3_Command" />
<asp:Button ID="Button4" runat="server" Text="三个参数" OnCommand="Button4_Command" />
<asp:Button ID="Button5" runat="server" Text="四个参数" OnClick="Button5_Click" />
</div>
</form>
</body>
</html>
在后台触发Button的单击事件,调用方法并弹出结果。
namespace WebApplication1
{
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
/// <summary>
/// 没有参数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Command(object sender, CommandEventArgs e)
{
Response.Write("<script>alert('" Override() "')</script>");
}
/// <summary>
/// 一个参数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button2_Command(object sender, CommandEventArgs e)
{
Response.Write("<script>alert('" Override(1) "')</script>");
}
/// <summary>
/// 两个参数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button3_Command(object sender, CommandEventArgs e)
{
Response.Write("<script>alert('" Override(1,"两个") "')</script>");
}
/// <summary>
/// 三个参数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button4_Command(object sender, CommandEventArgs e)
{
Response.Write("<script>alert('" Override(1,"三个",2.2f) "')</script>");
}
/// <summary>
/// 四个参数
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button5_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('" Override(1,"四个",2.2f,'a') "')</script>");
}
public string Override()
{
return "没有参数:";
}
public string Override(int a)
{
return "一个参数:" a;
}
public string Override(int a,string str)
{
return "两个参数: " a " " str;
}
public string Override(int a, string str,float b)
{
return "三个参数: " a " " str " " b;
}
public string Override(int a, string str, float b,char cha)
{
return "四个参数: " a " " str " " b " " cha;
}
}
}
赞 (0)