Csharp/CSharp Tutorial/Data Type/System Convert
Содержание
Convert a System.String into a System.Boolean using System.Convert
<source lang="csharp">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); }
}</source>
Convert.ToBoolean(theString) Type code string converted to bool is: Boolean Value of converted string: True
Convert.ChangeType
<source lang="csharp">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) ); }
}</source>
data type convert
<source lang="csharp">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); }
}</source>
Use System.Convert to convert string to Int16
<source lang="csharp">using System; class MainClass {
public static void Main(string[] argv) { int a = System.Convert.ToInt16("1"); int b = System.Convert.ToInt16("2"); }
}</source>