Csharp/CSharp Tutorial/Data Type/System Convert

Материал из .Net Framework эксперт
Версия от 12:18, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Convert a System.String into a System.Boolean using System.Convert

using System;
using System.Globalization;
class MainClass
{
  static void Main(string[] args)
  {      
    string theString = "true";
    Console.WriteLine("Convert.ToBoolean(theString)");        
    bool theBool = Convert.ToBoolean(theString);
    Console.WriteLine("Type code string converted to bool is: {0}", theBool.GetTypeCode());
    Console.WriteLine("Value of converted string: {0}", theBool);
  }
}
Convert.ToBoolean(theString)
Type code string converted to bool is: Boolean
Value of converted string: True

Convert.ChangeType

using System;
public sealed class ComplexNumber
{
    public ComplexNumber( double real, double imaginary ) {
        this.real = real;
        this.imaginary = imaginary;
    }
    private readonly double real;
    private readonly double imaginary;
}
public sealed class MainClass
{
    static void Main() {
        ComplexNumber num1 = new ComplexNumber( 1.12345678, 2.12345678 );
        string str = (string) Convert.ChangeType( num1, typeof(string) );
    }
}

data type convert

using System;
public class MainClass {
    static void Main(string[] args) {
        short shortResult, shortVal = 4;
        int integerVal = 67;
        long longResult;
        float floatVal = 10.5F;
        double doubleResult, doubleVal = 9999.999;
        string stringResult, stringVal = "17";
        bool boolVal = true;
        doubleResult = floatVal * shortVal;
        Console.WriteLine("Implicit, -> double: {0} * {1} -> {2}", floatVal, shortVal, doubleResult);
        shortResult = (short)floatVal;
        Console.WriteLine("Explicit, -> short:  {0} -> {1}", floatVal, shortResult);
        stringResult = Convert.ToString(boolVal) + Convert.ToString(doubleVal);
        Console.WriteLine("Explicit, -> string: \"{0}\" + \"{1}\" -> {2}", boolVal, doubleVal, stringResult);
        longResult = integerVal + Convert.ToInt64(stringVal);
        Console.WriteLine("Mixed,    -> long:   {0} + {1} -> {2}", integerVal, stringVal, longResult);
    }
}

Use System.Convert to convert string to Int16

using System;
class MainClass
{
    public static void Main(string[] argv)
    {
      int a = System.Convert.ToInt16("1");
      int b = System.Convert.ToInt16("2");
    }
}