摘要:C# override 改寫tostring
這個範例實作了employee類別的多載,並用override 改寫了tostring
因為id,name 是private,所以我們再建立一個建構函式public Employee(string id, string name)
來達成多載的目的,使得employee可以在宣告後,直接將id name的值給employee
以下是employee.cs
public class Employee
{
private string id;
private string name;
public Employee()
{
}
public Employee(string id, string name)
{
this.id = id;
this.name = name;
}
public override string ToString()
{
// return base.ToString();
return "編號:" + id +",姓名"+name;
}
}
以下是MainWindow.xaml.cs
private void button1_Click(object sender, RoutedEventArgs e)
{
Employee john = new Employee("1","JOHN");
Employee andy = new Employee();
label1.Content = john.ToString();
label2.Content = andy.ToString();
}
如有錯誤 歡迎指正