程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Part 57 to 58 Why should you override ToString and Equal Method,overridetostring

Part 57 to 58 Why should you override ToString and Equal Method,overridetostring

編輯:C#入門知識

Part 57 to 58 Why should you override ToString and Equal Method,overridetostring


Part 57 Why should you override ToString Method

sometimes you can override ToString method like that:

namepace Example

public class MainClass
{
  Customer C = new Customer();
  C.firstName = "Lin";
  C.lastName="Gester";
  Console.Write(C.ToString());  //it will write Lin Gester;
}
public class Customer
{
  public string FirstName{get;set;}
  public string LastName{get;set;}
  public override string ToString()
  {
    return this.FirstName+""+this.LastName;
  }
}

Part 58  Why should you override Equals Method

public class MainClass
{
    private static void Main()
    {
       Customer C1 = new Customer();
       C1.FirstName = "Lin"; 
       C1.LastName = "Gester";
       Customer C2 = new Customer();
       C2.FirstName = "Lin"; 
       C2.LastName = "Gester";
       Console.Write(C1==C2);
       Console.Write(C1.Equals(C2));
            
    }  
}
public class Customer
{
    public string FirstName{get;set;}
    public string LastName{get;set;}
    public override bool Equals(Object obj)
    {
        if(obj==null)
        {
            return false;
        }
        if(!(obj is Customer))
        {
            return false;
        }
        return this.FirstName==((Customer)obj).FirstName&&this.LastName==((Customer)obj).LastName;
    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved