Csharp/CSharp Tutorial/Development/Custom Format

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

Create customized format for Complex

using System;
using System.Text;
using System.Globalization;
public struct Complex : IFormattable
{
    public Complex( double real, double imaginary ) {
        this.real = real;
        this.imaginary = imaginary;
    }
    public string ToString( string format,IFormatProvider formatProvider ) {
        StringBuilder sb = new StringBuilder();
        if( format == "DBG" ) {
            sb.Append( this.GetType().ToString() + "\n" );
            sb.AppendFormat( "\treal:\t{0}\n", real );
            sb.AppendFormat( "\timaginary:\t{0}\n", imaginary );
        } else {
            sb.Append( "( " );
            sb.Append( real.ToString(format, formatProvider) );
            sb.Append( " : " );
            sb.Append( imaginary.ToString(format, formatProvider) );
            sb.Append( " )" );
        }
        return sb.ToString();
    }
    private double real;
    private double imaginary;
}
public class MainClass
{
    static void Main() {
        CultureInfo local = CultureInfo.CurrentCulture;
        CultureInfo germany = new CultureInfo( "de-DE" );
        Complex cpx = new Complex( 12.3456, 1234.56 );
        string strCpx = cpx.ToString( "F", local );
        Console.WriteLine( strCpx );
        strCpx = cpx.ToString( "F", germany );
        Console.WriteLine( strCpx );
        Console.WriteLine( "\nDebugging output:\n{0:DBG}", cpx );
    }
}
( 12.35 : 1234.56 )
( 12,35 : 1234,56 )
Debugging output:
Complex
        real:   12.3456
        imaginary:      1234.56

Custom Format Specifiers

Format Character     Purpose                                          
0                    Display zero placeholder
  
#                    Display digit placeholder
  
.                    Decimal point
  
,                    Group separator
  
%                    Percent notation
  
 
E+0                  Exponent notation
E-0
e+0
e-0
  
\                    Literal character
  
"ABC"                Literal string
"ABC"
  
;                    Section separator

Custom Object Formatting

using System;
class Employee: IFormattable
{
    int    id;
    string    firstName;
    string    lastName;
    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));
    }
}
class MainClass
{
    public static void Main()
    {
        Employee fred = new Employee(123, "First", "Last");
        Console.WriteLine("No format: {0}", fred);
        Console.WriteLine("Full format: {0:F}", fred);
    }
}
No format: 123
Full format: 123: Last, First

format as currency

using System;
  class Class1
  {
    static void Main(string[] args)
    {
            string s;
            int x = 2, y = 4;
            double[] numArray = {12, 15, 14.5, 145.43, 200};
            // format as currency
            Console.WriteLine( "\n\nCurrency\n--------" );
            foreach( double num in numArray )
            {
                Console.Write( "{0:C}\t", num );
            }
    }
  }

format as custom

using System;
  class Class1
  {
    static void Main(string[] args)
    {
            string s;
            int x = 2, y = 4;
            double[] numArray = {12, 15, 14.5, 145.43, 200};
            // format as custom
            Console.WriteLine( "\n\nCustom\n------" );
            foreach( double num in numArray )
            {
                Console.WriteLine( "{0:$#,# + $.#0;} = {0:$#,#.00}", num );
            }
    }
  }

format in lowercase hex

using System;
  class Class1
  {
    static void Main(string[] args)
    {
            string s;
            int x = 2, y = 4;
            double[] numArray = {12, 15, 14.5, 145.43, 200};
            // format in lowercase hex
            Console.WriteLine( "\n\nHex (lower)\n-----------" );
            foreach( double num in numArray )
            {
                Console.Write( "0x{0:x8}\t", (int)num );
            }
    }
  }

format in uppercase hex

using System;
  class Class1
  {
    static void Main(string[] args)
    {
            string s;
            int x = 2, y = 4;
            double[] numArray = {12, 15, 14.5, 145.43, 200};
            // format in uppercase hex
            Console.WriteLine( "\n\nHex (upper)\n-----------" );
            foreach( double num in numArray )
            {
                Console.Write( "0x{0:X8}\t", (int) num );
            }
    }
  }

Formatting flags

String            Description
C                 Local currency format.
D                 Decimal format.
E                 Scientific (exponential) format. 
F                 Fixed-point format; 
G                 General format. Uses E or F formatting, depending on which is the most compact.
N                 Number format. 
P                 Percent format.
X                 Hexadecimal format.

Formatting Using System.Console.WriteLine()

class MainClass
{
  static void Main()
  {
      string firstName;
      string lastName;
      firstName = "A";
      lastName = "B";
      System.Console.WriteLine("Your full name is {0} {1}.",firstName, lastName);
  }
}

Swapping the Indexed Placeholders and Corresponding Variables

class MainClass
{
  static void Main()
  {
      string firstName;
      string lastName;
      firstName = "A";
      lastName = "B";
      System.Console.WriteLine("Your full name is {1}, {0}",firstName, lastName);
  }
}

The value n various formats

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("c format: {0:c}", 99999);
      Console.WriteLine("d9 format: {0:d9}", 99999);
      Console.WriteLine("f3 format: {0:f3}", 99999);
      Console.WriteLine("n format: {0:n}", 99999);
    }
  }

Upper or lower casing for hex determines if letters are upper/lowercase

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("E format: {0:E}", 99999);
      Console.WriteLine("e format: {0:e}", 99999);
      Console.WriteLine("X format: {0:X}", 99999);
      Console.WriteLine("x format: {0:x}", 99999);
    }
  }

Using the \n Character to Insert a Newline

class MainClass
{
  static void Main()
  {
      System.Console.Write("\"this is a test.\"");
      System.Console.Write("\n\"Wait "til I get going!\"\n");
  }
}