重载 C#

关注我,为您分享C#技术实现

类成员

方法重载特点:

C# 方法是包含一系列语句的代码块

  1. 方法名必须相同
  2. 参数列表必须不相同
  3. 返回类型可以不相同

方法重载规则:

  1. 两方法不能仅在返回类型上有区分
  2. 两个方法不能仅根据参数是声明为ref还是out来区分

方法重载:

byte b1 = Convert.ToByte(true);

byte b2 = Convert.ToByte("123");

byte b3 = Convert.ToByte(3.14m);

代码示例:

public class Product

{

///

/// 修改,无参数

///

public void Modify()

{

}

///

/// 修改,int类型参数

///

/// i">参数i

///

public int Modify(int i)

{

return i;

}

///

/// 修改,string类型参数

///

/// s">参数s

///

public int Modify(string s)

{

return 1;

}

///

/// 修改,两个参数

///

/// s">参数s

/// i">参数i

///

public string Modify(string s,int i)

{

return "";

}

}

构造函数重载特点:

  1. 没有返回值。
  2. 方法名必须相同
  3. 参数列表必须不相同

运行结果:

private void button1_Click(object sender, EventArgs e)

{

try

{

int id = int.Parse(tb_id.Text);

string name = tb_name.Text;

string price = tb_price.Text;

Product p = new Product();

lbx_id.Text = p.Id.ToString();

lbx_name.Text = p.Name;

lbx_pric.Text = p.Price.ToString();


}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

//Product product = new Product();

//product.Modify("");

}

代码示例:

try

{

int id = int.Parse(tb_id.Text);

string name = tb_name.Text;

string price = tb_price.Text;

Product p = new Product(id,name);

lbx_id.Text = p.Id.ToString();

lbx_name.Text = p.Name;

lbx_pric.Text = p.Price.ToString();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

构造函数之间的调用:

运行结果:

调自己:this

///

/// 实例化一个id和名字的Product对象

///

/// _id">id

/// _name">名称

public Product(int _id,string _name)

:this(_id,_name,666)

{

id = _id;

name = _name;

}

调父类:(以后在讲)

代码示例:

public class Product

{

int id;

string name;

decimal price;

///

/// 实例化一个空的Product对象

///

public Product()

{

//空的构造函数

}

///

/// 实例化一个有id的Product对象

///

/// _id">id

public Product(int _id)

{

id = _id;

}

///

/// 实例化一个id和名字的Product对象

///

/// _id">id

/// _name">名称

public Product(int _id,string _name)

:this(_id,_name,666)

{

id = _id;

name = _name;

}

///

/// 实例化一个有id、名字、价格的Product对象

///

/// _id">id

/// _name">名称

/// _price">价格

public Product(int _id, string _name,decimal _price)

{

id = _id;

name = _name;

price = _price;

}

public int Id { get => id; set => id = value; }

public string Name { get => name; set => name = value; }

public decimal Price { get => price; set => price = value; }

#region 重载方法示例

///

/// 修改,无参数

///

public void Modify()

{

}

///

/// 修改,int类型参数

///

/// i">参数i

///

public int Modify(int i)

{

return i;

}

///

/// 修改,string类型参数

///

/// s">参数s

///

public int Modify(string s)

{

return 1;

}

///

/// 修改,两个参数

///

/// s">参数s

/// i">参数i

///

public string Modify(string s,int i)

{

return "";

}

#endregion

}

展开阅读全文

页面更新:2024-06-08

标签:法名   示例   函数   实例   对象   名字   参数   类型   代码   方法

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top