C# study notes–Conversion of variable types
Conversion of variable type:
Conversion principle: Large ones of the same type can be installed into small ones, and forced conversion is required to install large ones into small types.
Implicit conversion:
Conversion of the same type:
//Signed long——>int——>short——>sbyte
long l = 1;
int i = 1;
short s = 1;
sbyte sb = 1;
//Implicit conversion int is implicitly converted to long
//You can use a large range to install a small range of types (implicit conversion)
l = i;
//You cannot use a small range type to fit a large range type
//i = l;
l = i;
l = s;
l = sb;
i = s;
s = sb;
ulongul = 1;
uint ui = 1;
ushort us = 1;
byte b = 1;
ul = ui;
ul = us;
ul = b;
ui = us;
ui = b;
us = b;
//Floating point number decimal double——>float
decimal = 1.1m;
double d = 1.1;
float f = 1.1f;
//There is no way to store double and float in the form of implicit conversion for the decimal type.
//de = d;
//de = f;
//float can be implicitly converted to double
d = f;
//Special type bool char string
// There is no implicit conversion between them
bool bo = true;
char c = 'A';
string str = "123123";
//Special type bool char string
// There is no implicit conversion between them
Different types of conversions:
The char type can be implicitly converted to a numeric type and converted according to the corresponding ASCII code.
Unsigned cannot implicitly store signed, while signed can store unsigned.
Show Transformation
-
Forced bracket conversion (pay attention to accuracy issues and range issues)
//Signed type int i=1; short s=(short)i; //unsigned type byte b=1; uint ui=(uint)b; //Floating point number float f=1.5f; double d=1.5; f=(float)d; //Unsigned and signed //Make sure to be positive and pay attention to the range int ui2=1; int i2=1; ui2=(uint)i2; //floating point and integer i2=(int)1.25f; //char and numerical types i2='A'; char c=(char)i2;
-
Parse method
//Parse conversion int i4=int.Parse("123"); float f4=float.Parse("12.3"); //Pay attention to type and scope!
-
Convert method
int a=Convert.ToInt32("12"); a=Convert.ToInt32("1.35f");//will be rounded a=Convert.ToInt32(true);//convert to 1 false to 0
Note: In the Convert conversion, the variable is int, for example, INT16 is int, ToSingle is float
ToDouble is double, ToBoolean is bool;
-
Convert other types to string (call ToString method)
string str=true.ToString();
string str2=1.5f.ToString();