The conversion of reference types has implicit conversions, casts, as conversions, and so on. There are many ways to convert value types, which are summarized in this article.
-Implicit conversion
int i = 10;
float f = i;
Console.WriteLine (f);
In the case of a value type, an implicit conversion can be achieved when the numeric range of the converted variable is less than the range of the target variable, and if it is a reference type, the subclass can be implicitly converted to the parent class.
-Cast
float f = 10.56f;
int i = (int) F;
Console.WriteLine (i);
If it is a value type, consider casting if the value range of the converted variable is greater than the array range of the target variable, and if it is a reference type, the parent class can be cast to a subclass. It is important to note that casting may result in some loss of precision.
-Convert by static method of System.Convert
such as converting an integral type into Sysem.Char a type.
char result = Convert.tochar (68);
Console.WriteLine (result);
PassSystem.ConvertConversion failures are reportedOverflowExceptionAbnormal.
-static method by value type
Converts a string to an int type.
string str = "one";
int int. Parse (str);
Console.WriteLine (i);
If the string contains non-numbers, it throws system.formatexception exception.
string str = "11a";
int int. Parse (str);
Console.WriteLine (i);
How to avoid this situation?
-- int.TryParse Use the method to avoid this situation.
string str = "11a";
int result = 1;
BOOL int out result);
if (issuccess)
{
Console.WriteLine (result);
}
Else
{
Console.WriteLine (" conversion failed ");
}
-Via IConvertible interface method
Because all value types implement an IConvertible interface, you can implement value type conversions through the interface's methods.
char result = ((iconvertible) 68). ToChar (null );
console.writeline (result);
If the conversion fails, an System.InvalidCastException exception is thrown.
Several ways to convert value types