数值提升
表达式的数据类型是各数据最高的数据类型
表达式也有类型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 表达式类型
{
class Program
{
static void Main(string[] args)
{
int a = 100;
int b;
Console.WriteLine(b=a);
Console.WriteLine((b=a).GetType().FullName);
}
}
}
//运行结果:100
//System.Int32
查看经过VS编译后的低级源代码
- 打开文件代码在资源管理器中的位置
-
依次打开bin-debug:在里面可以看见编译后生成的.exe文件
-
选择VS工具:Developer Command Prompt for VS 2019
-
在弹出的控制台中输入:ildasm,将程序拖入窗口程序中,就可以看见程序结构
-
双击对应的函数就可以看见CPU的执行语句
-
语句的定义
陈述算法思想,控制逻辑走向,完成有意义的动作
C#的程序以“;”结束,但是由分号结尾的不一定是语句(引入名称空间的代码,虽然他是以";"结尾,但是他不是语句。同样的,字段的声明也不是语句)
语句一定要出现在方法体里面
处理输入的类型错误
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 异常处理
{
class Program
{
static void Main(string[] args)
{
string a = Console.ReadLine();
try
{
double t = double.Parse(a);
if (t>69)
{
Console.WriteLine("这是一个大于69的数");
}
else
{
Console.WriteLine("这个数字小于69");
}
}
catch //用于处理可能出现的所有错误
{
Console.WriteLine("这不是一个数字");
}
}
}
}
//输入:34 输出:这个数字小于69
//输入:dgwywqgqwu 输出:这不是一个数字
语句的详解
标签语句(不常见)
声明语句
嵌入式语句
嵌入结构:例如:if嵌套的语句(块语句)
循环语句
- while语句
注意使用try-catch语句处理可能出现的异常(类型异常和超限异常)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 循环结构
{
class Program
{
static void Main(string[] args)
{
try
{
bool run_or_not = true;
while (run_or_not)
{
Console.WriteLine("请输入第一个数字");
int first_number = Int16.Parse(Console.ReadLine());
Console.WriteLine("请输入第二个数字");
int second_number = Int16.Parse(Console.ReadLine());
int sum = first_number + second_number;
run_or_not = (sum == 100) ? false : true;
if(run_or_not)
{
Console.WriteLine("你输入的数字和不为100!");
}
else
{
Console.WriteLine("你输入的数字和为1003");
}
}
}
catch (FormatException)
{
Console.WriteLine("对不起你输入的内容格式不正确!!!!");
}
catch(OverflowException)
{
Console.WriteLine("对不起您输入的数值太大了!!");
}
}
}
}
continue-break
continue是放弃当前执行的循环,然后开始下一次的循环;而break是直接跳出循环,所有循环都将不再执行。
foreach
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace foreach语句
{
class Program
{
static void Main(string[] args)
{
int[] intArray = new int[] { 1, 2, 3, 4, 5, 6 };
foreach (var i in intArray)
{
Console.WriteLine(i);
}
}
}
}
return
尽早return原则:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 尽早return原则
{
class Program
{
static void Main(string[] args)
{
string name = "Jom";
Greeting(name);
Greeting2(name);
name = "";
Greeting(name);
Greeting2(name);
}
static void Greeting(string name) //原始表达
{
if (!string.IsNullOrEmpty(name))
{
Console.WriteLine("Hello1,{0}!",name);
}
}
static void Greeting2(string name) //尽早return
{
if (string.IsNullOrEmpty(name))
{
return; //此处有return语句,将不会再执行后面的语句
}
Console.WriteLine("Hello2,{0}!", name);
}
}
}
//运行结果: Hello1,Jom!
// Hello2,Jom!