1. C# type conversion
Meaning : Convert data from one type to another type (also called type casting); there are two conversion methods in C#:
- Implicit type conversion; eg: from a small integer to a large integer type, from a derived class to a base class;
- Explicit casts; that is, casts, which require a cast operator and cause data loss;
the demo below shows explicit casts:
double d = 1265.66;
int i;
i = (int)d;
Console.WriteLine("强制类型转换的结果为:{0}", i);
Console.ReadKey();
The running result is:
2. C# Coercion Type Conversion Methods
C# provides the following built-in type conversion methods
The following demo converts different value types to string types
class Program
{
//JdJos.Rectangle rectangle = new JdJos.Rectangle();
static void Main(string[] args)
{
int i = 88;
float f = 56.25f;
double d = 894.59489;
bool b = true;
Console.WriteLine("将整型转换为string类型:{0}", i.ToString());
Console.WriteLine("将float转换为string类型:{0}", f.ToString());
Console.WriteLine("将double转换为string类型:{0}", d.ToString());
Console.WriteLine("将bool转换为string类型:{0}", b.ToString());
Console.ReadKey();
}
}
The running result is:
Notes:
Converting between types ------ Convert and Parse
String str = 666.ToString();
//如果要将str转为整型
//方法一:
int istr = Convert.ToInt16(str);
//方法二:
int istr2 = int.Parse(str);
Console.WriteLine("使用Convert将String类型转为int类型结果为:{0},使用Parse将同样数据转为int类型的结果为:{1}", istr, istr2);
Console.ReadKey();
The running result is:
int.TryParse(string s, out int i);
This method is also to convert the string of the array content to int type, but this method is better than int.Parse(string s), it will not cause exception, the last parameter result is the output value, if the conversion is successful, the corresponding value will be output , if the conversion fails, output 0.
String s1 = "abcd";
String s2 = "1234";
int a, b;
bool bol = int.TryParse(s1, out a);
Console.WriteLine("====================将string类型的abcd转为int类型======================");
if(bol ==true)
{
Console.WriteLine("转换成功,abcd转为int类型结果为:{0}", a);
}else
{
Console.WriteLine("转换失败,abcd转为int类型转换失败:{0},转换结果为{1}",bol, a);
}
Console.WriteLine("====================将string类型的1234转为int类型====================");
bool bol2 = int.TryParse( s2,out b);
if (bol2 == true)
{
Console.WriteLine("转换成功,s2的{0}转为int类型结果为:{1}", s2, b);
}
else
{
Console.WriteLine("转换失败,1234转为int类型转换失败:{0},转换结果为{1}", bol2, a);
}
Console.ReadKey();
To round the data of double type in C#, you can use the convert.toint32() method, or you can use int to cast the type to integer. When using int, there is no rounding , but directly discard the following decimal places. eg:
static void Main(string[] args)
{
double a = 1.256;
double b = 826.66649;
int a1 = Convert.ToInt32(a);
int a2=(int)a;
int b1 = Convert.ToInt32(b);
int b2 = (int)b;
Console.WriteLine("{0}使用了convert方式强制类型转换,结果为:{1}", a, a1);
Console.WriteLine("{0}使用了int强制类型转换,结果为:{1}", a, a2);
Console.WriteLine("{0}使用了convert方式进行强制类型转换,结果为{1}",b, b1);
Console.WriteLine("{0}使用了int方式强制类型转换,结果为{1}", b, b2);
Console.ReadKey();
}
The running result is:
The difference between Convert.ToInt32() and int.Parse()
For example: if you take the value of a parameter page from the url, this value is of type int, so you can use Convert.ToInt32(Request.QueryString["page"] ), you can also use int.Parse(Request.QueryString["page"]), but if the page parameter does not exist in the url, then the former will return 0, 0 may be a valid value, so you don't know the url It turns out that there is no such parameter at all and the next step is processed, which may produce unexpected effects. In the latter method, if there is no page parameter, an exception will be thrown . We can catch the exception and then deal with it accordingly. , such as prompting the user that a parameter is missing, instead of treating the parameter value as 0.
(1) The biggest difference between these two methods is that they deal with null values: Convert.ToInt32(null) will return 0 without generating any exception, but int.Parse(null) will generate an exception.
(2), the difference when rounding the data
a, Convert.ToInt32 (double value) If the value is a number between two integers, then return the even number of the two; that is, 3.5 is converted to 4, 4.5 is converted to 4, and 5.5 is converted to 4. The conversion bit is 6. However, 4.6 can be converted to 5, and 4.4 can be converted to 4.
b.int.Parse("4.5") directly reports an error: "The input string format is incorrect".
c.int(4.6)=4 When int converts other numeric types to int, there is no rounding and coercion.
(3) The difference between the converted types: int.Parse converts String to int, Convert.ToInt32 converts objects inherited from Object to int (there can be many other types of data). youGet an Object object , you want to convert it to int, you can't use int.Parse, use Convert.ToInt32.
String to int and throw exception
string string type and int can be converted. But the conversion method of the following demo is wrong:
string a = "123";
int x = (int)a;
Here we need to apply to int.Parse(), the core code is:
string a = "123";
int x = int.Parse(a);
If it is just like this, there is no problem, but let's do an example below. The user enters a number, and the computer adds 1 to the entered number and displays it. The user input, that is, Console.ReadLine(), must be expressed in the form of a string .
Console.WriteLine("请输入一个数字:");
int a = int.Parse(Console.ReadLine());//将用户输入的string类型转为int类型
Console.WriteLine("您输入的数字为:{0}, 返回结果为:{1}", a, ++a);
Console.ReadKey();
Running result:
But what will happen if the user inputs other characters instead of numbers, such as strings and Chinese characters?
Input any character string or Chinese character, the program will report an error and cannot go on, because the int type can only store integers, not characters.
So use try and catch to be on the safe side. As the name suggests, try{} is to try the following code, and the catch{} part is to check for exceptions. In this way, when an exception occurs, the catch can catch the exception, so that the program will not stop.
try
{
Console.WriteLine("请输入一个数字:");
int a = int.Parse(Console.ReadLine());//将用户输入的string类型转为int类型
Console.WriteLine("您输入的数字为:{0}, 返回结果为:{1}", a, ++a);
}
catch
{
Console.WriteLine("对不起,输入不合法,无法转换。");
}
Console.ReadKey();
operation result:
C# variables
A variable is the name of a memory area for the program to manipulate. In C#, each variable has a specific type, the type determines the memory size and distribution of the variable, the value within the range can be stored in the memory, and a series of operations can be performed on the variable. . The basic value types provided in C# can be roughly divided into the following categories:
C# allows the definition of variables of other values, such as: enum, and also allows the definition of reference type variables, such as class.
Definition of variables in C#
<有效的C#数据类型{char,int,float,double或其他用户自定义的数据类型}> <由一个或多个逗号分隔的标识符名称组成>
eg: Some valid variable name definitions:
int i, j, k;
char c, ch;
float f, f1;
double d;
int i1 = 100;//定义时候直接初始化
C# variable initialization - assignment
eg:
int i = 66, k = 5;
byte z = 66;
double pi = 3.1415926;
char x = 'x';//注意这里是单引号
Accept the value from the user The
Console class in the System namespace provides a function ReadLine() to receive input from the user and store it in a variable, eg:
int num;
num = Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32() converts the data entered by the user to int.
Lvalues and Rvalues in
C# There are two types of expressions in C#:
1. lvalue:lvalue expressions can appear on the left or right side of an assignment statement;
2. rvalue:rvalue expressions can appear on the right side of an assignment statement, but not on the left side.
Variables are lvalues, so they can appear on the left side of assignment statements. Values are rvalues, so they cannot be assigned and cannot appear on the left side of an assignment statement; eg:
int g = 20;
33 = 60;//invalid assignment sentence
C# constants
Constants are fixed values that do not change during execution and can be of any basic data type, eg: integer constants, floating point constants, character constants or string constants, enum constants. Their values cannot be modified after they are defined.
Integer constants
can be decimal, octal, or hexadecimal constants. The prefix specifies the technique: 0x or 0X for hexadecimal, 0 for octal, and no prefix for decimal.
Constants can have suffixes. U and L are combined, representing unsigned and long respectively. The suffixes are in any case, and multiple suffixes can be combined in any order.
212 /* 合法 */
215u /* 合法 */
0xFeeL /* 合法 */
078 /* 非法:8 不是一个八进制数字 */
032UU /* 非法:不能重复后缀 */
The following are examples of integer constants of various types:
85//十进制
0213 //八进制
0xbd4 //十六进制
30 //int
66u //无符号int
99l //long
99ul //无符号long
Floating point constant
eg:
3.1415926 //合法
314159E -5L //合法
510E //非法,不完全指数
210f //非法,没有小数或指数
.e55 //非法,缺少整数或小数
When expressed in decimal form, it must contain a decimal point, an exponent, or both, and when expressed in exponential form, it must contain an integer part, a fractional part, or both. Signed exponents are denoted by e or E.
character constant
Character constants are enclosed in single quotes, eg: 'x', and can be stored in a simple character type variable. A character constant can be an ordinary character (eg'X'), an escape sequence (eg'\t'), or a general character (eg'\u02c0').
There are certain characters that are signed with backslashes when they are signed The bar has a special meaning and can represent a newline (\n) or a tab (\t)
String constants
String constants are enclosed in double quotes "", or in @"". String constants contain characters similar to character constants. Can be ordinary characters, escape characters, and general characters.
Defining
constants Constants are defined using the const keyword. The syntax is as follows:
const <类型> <常量名>=value;
The following demo shows how to use constants:
static void Main(string[] args)
{
const double pi = 3.141592653;
double r;
Console.WriteLine("Enter Radius of Integer:");
r = Convert.ToInt32(Console.ReadLine());
double areaCircle = pi * r * r;
Console.WriteLine("Radius:{0},Area:{1}", r, areaCircle);
Console.ReadKey();
}
operation result:
Notes:
1. The difference between Convert.ToDouble and Double.Parse. In fact, Convert.ToDouble internally calls Double.Parse:
(1), when the parameter is null: If the parameter of
Convert.ToDouble is null, it returns 0.0;
when the parameter of Double.Parse is null, an exception is thrown;
(2), When the parameter is "": When the
Convert.ToDouble parameter is "", an exception is thrown; when the
Double.Parse parameter is "", an exception is thrown.
(3) Other differences:
Convert.ToDouble can convert many types;
Double.Parse can only convert numeric strings. Double.TryParse is similar to Double.Parse
, but it does not generate an exception. It returns true if the conversion is successful, and false if the conversion fails. The last parameter is the output value. If the conversion fails, the output value is 0.0;
Class strings are converted in three ways:
Case 2: Convert null type strings in three ways:
Case 3: Convert "" type strings in three ways: The
test demo is:
static void Main(string[] args)
{
try
{
//string a = "0.2";//没有走try里面的数据
//String a = null;
string a = "";
Console.WriteLine("将字符串为空通过下面三种方式进行转换为double类型:",a);
try
{
double d1 = Double.Parse(a);
Console.WriteLine("{0}通过Double.Parse转换成功结果为:{1}。", a,d1);
}
catch(Exception e)
{
Console.WriteLine("{0}通过Double.Parse转换出错信息:{1}。", a, e.Message);
}
Console.WriteLine();
Console.WriteLine("使用Double.Parse转换进行转换:");
try
{
double d2 = Convert.ToDouble(a);
Console.WriteLine("{0}通过Double.Parse转换成功结果为:{1}", a, d2);
}
catch(Exception e)
{
Console.WriteLine("{0}通过Convert.ToDouble方式转换错误:{1}", a, e.Message);
}
Console.WriteLine();
Console.WriteLine("使用Double.TryParse进行转换:");
try
{
double d3;
Double.TryParse(a, out d3);
Console.WriteLine("{0}通过Double.TryParse转换成功结果为:{1}", a, d3);
}
catch(Exception e)
{
Console.WriteLine("{0}通过Double.TryParse方式转换错误:{1}", a,e.Message);
}
}finally
{
Console.WriteLine();
Console.WriteLine("finally方法一定走");
Console.ReadKey();
}
}