Csharp/C Sharp/Class Interface/ToString — различия между версиями

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

Версия 15:31, 26 мая 2010

class declaration maintains the time in 24-hour format and ToString Method

using System;
public class Time1
{
   private int hour; // 0 - 23
   private int minute; // 0 - 59
   private int second; // 0 - 59
   public void SetTime( int h, int m, int s )
   {
      hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); 
      minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
      second = ( ( s >= 0 && s < 60 ) ? s : 0 );
   } 
   public string ToUniversalString()
   {
      return string.Format( "{0:D2}:{1:D2}:{2:D2}",
         hour, minute, second );
   } 
   public override string ToString()
   {
      return string.Format( "{0}:{1:D2}:{2:D2} {3}",
         ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
         minute, second, ( hour < 12 ? "AM" : "PM" ) );
   } 
}
public class Time1Test
{
   public static void Main( string[] args )
   {
      Time1 time = new Time1(); 
      Console.WriteLine( time.ToUniversalString() );
      Console.WriteLine( time.ToString() );
      time.SetTime( 13, 27, 6 );
      Console.WriteLine( time.ToUniversalString() );
      Console.WriteLine( time.ToString() );
      time.SetTime( 99, 99, 99 );
      Console.WriteLine( time.ToUniversalString() );
      Console.WriteLine( time.ToString() );
   }
}


demonstrates overriding the ToString() method to provide a custom string output

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//  tm1.cs - demonstrates overriding the ToString() method to provide a custom
//           string output.
//
//           Compile this program using the following command line:
//               D:>csc tm1.cs
//
namespace nsStructure
{
    using System;
    using System.Globalization;
    public struct tm
    {
        public int tm_sec;       // Seconds after the minute
        public int tm_min;       // Minutes after the hour 
        public int tm_hour;      // Hours since midnight
        public int tm_mday;      // The day of the month
        public int tm_mon;       // The month (January = 0)
        public int tm_year;      // The year (00 = 1900)
        public int tm_wday;      // The day of the week (Sunday = 0)
        public int tm_yday;      // The day of the year (Jan. 1 = 1)
        public int tm_isdst;     // Flag to indicate if DST is in effect
        public override string ToString()
        {
            const string wDays = "SunMonTueWedThuFriSat";
            const string months = "JanFebMarAprMayJunJulAugSepOctNovDec";
            return (String.Format ("{0} {1} {2,2:00} " + 
                            "{3,2:00}:{4,2:00}:{5,2:00} {6}\n", 
                             wDays.Substring (3 * tm_wday, 3),
                             months.Substring (3 * tm_mon, 3),
                             tm_mday, tm_hour, tm_min,
                             tm_sec, tm_year + 1900));
        }
    }
    public class tm1
    {
        static public void Main()
        {
            DateTime timeVal = DateTime.Now;
            tm tmNow = LocalTime (timeVal);
            Console.WriteLine (tmNow);
        }
        static public tm LocalTime(DateTime tmVal)
        {
            tm time;
            time.tm_sec = tmVal.Second;
            time.tm_min = tmVal.Minute;
            time.tm_hour = tmVal.Hour;
            time.tm_mday = tmVal.Day;
            time.tm_mon = tmVal.Month - 1;
            time.tm_year = tmVal.Year - 1900;
            time.tm_wday = (int) tmVal.DayOfWeek;
            time.tm_yday = tmVal.DayOfYear;
            TimeZone tz = TimeZone.CurrentTimeZone;
            time.tm_isdst = tz.IsDaylightSavingTime (tmVal) == true ? 1 : 0;
            return (time);
        }
    }
}


Demonstrate ToString()

/*
C#: The Complete Reference 
by Herbert Schildt 
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/

// 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; 
  } 
} 
 
public class Test { 
  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); 
 
  } 
}


Format data in ToString method.

using System;
public class Time1
{
   private int hour; 
   private int minute; 
   private int second;
   public void SetTime( int h, int m, int s )
   {
      hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); 
      minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); 
      second = ( ( s >= 0 && s < 60 ) ? s : 0 ); 
   } 
   public string ToUniversalString()
   {
      return string.Format( "{0:D2}:{1:D2}:{2:D2}", hour, minute, second );
   } 
   public override string ToString()
   {
      return string.Format( "{0:D2}:{1:D2}:{2:D2} {3}",
         ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
         minute, second, ( hour < 12 ? "AM" : "PM" ) );
   } 
}
public class MemberAccessTest
{
   public static void Main( string[] args )
   {
      Time1 time = new Time1(); 
      time.hour = 7; // error: hour has private access in Time1
      time.minute = 15; // error: minute has private access in Time1
      time.second = 30; // error: second has private access in Time1
   }
}


Illustrates how to override the ToString() method

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
  Example7_7.cs illustrates how to override the ToString() method
*/
using System;

// declare the Car class
class Car
{
  // declare the fields
  public string make;
  public string model;
  // define a constructor
  public Car(string make, string model)
  {
    this.make = make;
    this.model = model;
  }
  // override the ToString() method
  public override string ToString()
  {
    return make + " " + model;
  }
}

public class Example7_7
{
  public static void Main()
  {
    // create Car objects
    Console.WriteLine("Creating Car objects");
    Car myCar = new Car("Toyota", "MR2");
    Car myOtherCar = new Car("Porsche", "Boxter");
    // call the ToString() method for the Car objects
    Console.WriteLine("myCar.ToString() = " +
      myCar.ToString());
    Console.WriteLine("myOtherCar.ToString() = " +
      myOtherCar.ToString());
  }
}


.NET Frameworks Overview:Custom Object Formatting

using System;
class Employee: IFormattable
{
    public Employee(int id, string firstName, string lastName)
    {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public string ToString (string format, IFormatProvider fp) 
    {
        if ((format != null) && (format.Equals("F")))
        return(String.Format("{0}: {1}, {2}", 
        id, lastName, firstName));
        else
        return(id.ToString(format, fp));
    }
    int    id;
    string    firstName;
    string    lastName;
}
public class CustomObjectFormatting
{
    public static void Main()
    {
        Employee fred = new Employee(123, "AAA", "BBB");
        Console.WriteLine("No format: {0}", fred);
        Console.WriteLine("Full format: {0:F}", fred);
    }
}


Overriding the ToString() Method

using System;
   
public class Name {
  public string firstName;
  public string lastName;
   
  public Name(string firstName, string lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
   
  public void Display() {
    Console.WriteLine("firstName = " + firstName);
    Console.WriteLine("lastName = " + lastName);
  }
   
  // override the ToString() method
  public override string ToString() {
    return firstName + " " + lastName;
  }
}
class Test{
  public static void Main() {
    Name myName = new Name("T", "M");
    Name myOtherName = new Name("P", "B");
   
    // call the ToString() method for the Name objects
    Console.WriteLine("myName.ToString() = " + myName.ToString());
    Console.WriteLine("myOtherName.ToString() = " + myOtherName.ToString());
  }
}