Csharp/CSharp Tutorial/Development/Custom Format

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

Create customized format for Complex

<source lang="csharp">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 );
   }

}</source>

( 12.35 : 1234.56 )
( 12,35 : 1234,56 )
Debugging output:
Complex
        real:   12.3456
        imaginary:      1234.56

Custom Format Specifiers

<source lang="csharp">Format Character Purpose 0 Display zero placeholder

  1. 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</source>

Custom Object Formatting

<source lang="csharp">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);
   }

}</source>

No format: 123
Full format: 123: Last, First

format as currency

<source lang="csharp">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 );
           }
   }
 }</source>

format as custom

<source lang="csharp">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 );
           }
   }
 }</source>

format in lowercase hex

<source lang="csharp">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 );
           }
   }
 }</source>

format in uppercase hex

<source lang="csharp">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 );
           }
   }
 }</source>

Formatting flags

<source lang="csharp">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.</source>

Formatting Using System.Console.WriteLine()

<source lang="csharp">class MainClass {

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

}</source>

Swapping the Indexed Placeholders and Corresponding Variables

<source lang="csharp">class MainClass {

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

}</source>

The value n various formats

<source lang="csharp">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);
   }
 }</source>

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

<source lang="csharp">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);
   }
 }</source>

Using the \n Character to Insert a Newline

<source lang="csharp">class MainClass {

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

}</source>