Csharp/CSharp Tutorial/Class/ToString

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Demonstrate ToString()

using System; 
 
class MyClass { 
  static int count = 0; 
  int id; 
 
  public MyClass() { 
    id = count; 
    count++; 
  } 
 
  public override string ToString() { 
    return "MyClass object #" + id; 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    MyClass ob1 = new MyClass(); 
    MyClass ob2 = new MyClass(); 
    MyClass ob3 = new MyClass(); 
 
    Console.WriteLine(ob1); 
    Console.WriteLine(ob2); 
    Console.WriteLine(ob3); 
 
  } 
}
MyClass object #0
MyClass object #1
MyClass object #2

How to override the ToString() method

using System;
public class Employee
{
  public string firstName;
  public string lastName;
  public Employee(string firstName, string lastName)
  {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  public override string ToString()
  {
    return firstName + " " + lastName;
  }
}
class MainClass
{
  public static void Main()
  {
    Employee myEmployee = new Employee("A", "M");
    Employee myOtherEmployee = new Employee("B", "N");
    Console.WriteLine("myEmployee.ToString() = " + myEmployee.ToString());
    Console.WriteLine("myOtherEmployee.ToString() = " + myOtherEmployee.ToString());
  }
}
myEmployee.ToString() = A M
myOtherEmployee.ToString() = B N

mark override when overriding ToString

using System;
public class Thing {
    public int i = 2;
    public int j = 3;
    override public string ToString() {
        return String.Format("i = {0}, j = {1}", i, j);
    }
}

override ToString

using System;
using System.Collections;
   
struct RGB
{
    public int red;
    public int green;
    public int blue;
   
    public RGB(int red, int green, int blue)
    {
        this.red = red;
        this.green = green;
        this.blue = blue;
    }
   
    public override String ToString()
    {
        return red.ToString("X") 
            + green.ToString("X") 
            + blue.ToString("X");
    }
}
   
class BoxTest
{
    static ArrayList rgbValues;
   
    public static void Main()
    {
        RGB rgb = new RGB(255, 255, 255);
   
        rgbValues = new ArrayList();
        rgbValues.Add(rgb);
   
        Console.WriteLine("The RGB value is {0}", rgb);
    }
}