Several types of value type conversion
The conversion methods of reference types include implicit conversion, forced conversion, and as conversion. There are also many conversion methods for value types. This article will summarize them slightly.
□Implicit Conversion
int i = 10;
float f = i;
Console.WriteLine(f);
If it is a value type, you can implement implicit conversion when the value range of the converted variable is smaller than the value range of the target variable. If it is a reference type, the subclass can be implicitly converted to the parent class.
□Forced Conversion
float f = 10.56f;
int i = (int) f;
Console.WriteLine(i);
If it is a value type, when the value range of the converted variable is greater than the array range of the target variable, use forced conversion. If it is a reference type, the parent class can be forcibly converted to a subclass. It is worth noting that forced conversion may cause loss of precision.
□Implement conversion through the static method of System. Convert
For example, convert an integerSysem.Char
Type.
char result = Convert.ToChar(68);
Console.WriteLine(result);
PassSystem.Convert
If the conversion fails, an error is reported.OverflowException
Exception.
□Static method of Value Type
Converts a string to the int type.
string str = "11";
int i = int.Parse(str);
Console.WriteLine(i);
If the string contains non-numbersSystem.FormatException
Exception.
string str = "11a";
int i = int.Parse(str);
Console.WriteLine(i);
How can this problem be avoided?
-- Useint.TryParse
This can be avoided.
string str = "11a";
int result = 1;
bool isSuccess = int.TryParse(str, out result);
if (isSuccess)
{
Console.WriteLine(result);
}
else
{
Console. WriteLine ("Conversion failed ");
}
□Using the IConvertible Interface
Because all value types are implementedIConvertible
Interface, which can be used to convert the value type.
char result = ((IConvertible) 68).ToChar(null);
Console.WriteLine(result);
If the conversion failsSystem.InvalidCastException
Exception.