Csharp/C Sharp/Data Types/Convert

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

Convert string to int

<source lang="csharp">

using System; using System.Collections.Generic; using System.Text; class Program {

   static void Main(string[] args) {
       Console.WriteLine("Enter an integer:");
       int myInt = Convert.ToInt32(Console.ReadLine());
       Console.WriteLine("Integer less than 10? {0}", myInt < 10);
       Console.WriteLine("Integer between 0 and 5? {0}",
                         (0 <= myInt) && (myInt <= 5));
       Console.WriteLine("Bitwise AND of Integer and 10 = {0}", myInt & 10);
   }

}

</source>


Hidden among the To(integral-type) methods are overloads that parse numbers in another base:

<source lang="csharp"> using System; public class MainClass {

   public static void Main() {
       int thirty = Convert.ToInt32("1E", 16);      // parse in hexadecimal
       uint five = Convert.ToUInt32("101", 2);      // parse in binary
   }

}

</source>


The source and target types must be one of the "base" types. ChangeType also accepts an optional IFormatProvider argument. Here"s an example:

<source lang="csharp"> using System; public class MainClass {

   public static void Main() {
       Type targetType = typeof(int);
       object source = "42";
       object result = Convert.ChangeType(source, targetType);
       Console.WriteLine(result);             // 42
       Console.WriteLine(result.GetType());   // System.Int32
   }

}

</source>