正文
目录会跟随阅读位置移动。
阅读进度

using System;
namespace ConsoleAPP1//命名空间,项目名
{
class Program//文件名
{
static void Main(string[] args)//main函数,从main开始
{
}
}
}
输出
Console.WriteLine("Hello, World!");//输出一行,直接换行
Console.Write("Hello, ");
Console.Write("World!");//输出一行,但是不会换行
输入
Console.ReadLine();//输入一行需要换行才能看作输入
Console.ReadKey();//输入一个就看作输入
## 整数
### 有符号(大类型)
sbyte int short long(最大值不同,有正负)
### 无符号(大类型)
byte uint ushort ulong (最大值不同,无正负)
## 浮点数
float double decimal(有效数字不同)
## 字符
char
## 布尔
bool
## 字符串
string
\\'单引号
\"双引号
\\反斜杠
\0空字符
\n换行
\t制表符(tab)
\r回车
\b退格
\a响铃
## 取消转义字符
//取消了@后面的转义字符的作用
string str=@"hello/world";
Console.WriteLine(str);
/or
Console.WriteLine(@"hello/world");
//大范围装小范围的类型,但是要求是相同大类型
//例:
sbyte s = 1;
int b = s;
//注意:浮点数类型只有float和double可以转换,decimal不行
//char和string不存在隐式转换
无符号可以装有符号的,但是有符号不能隐式转换为无符号
// ------------------------------
// 1️ 无符号可以隐式装有符号
// ------------------------------
int signedInt = 100;
uint unsignedInt = (uint)signedInt; // 需要显示转换,因为 int → uint 可能溢出
// 注意:C# 不允许 int -> uint 隐式转换
// uint u = signedInt; // 编译错误
有符号也可以装无符号,但是必须涵盖在有符号大小里面
// ------------------------------
// 2️ 有符号可以装无符号,但是必须涵盖大小
// ------------------------------
byte uByte = 200;
int sInt = uByte; // byte 小于 int,可以隐式转换
ushort uShort = 60000;
// short sShort = uShort; // 超过 short.MaxValue,必须显示转换
short sShortSafe = (short)uShort; // 数据可能溢出
-浮点数可以装任意整型(隐式转换) 整型不能装浮点数(可能丢失精度,需要显式转换)
int n = 100;
double pi = n; // int → double 自动转换
double dNum = 3.14;
// int n2 = dNum; // 编译错误,需要显式转换
int n2 = (int)dNum; // 3,截断小数部分
只有char可以转换为整形和浮点型,根据ASCII码表看转换的是什么
char c = 'A';
int ascii = c; // 65
double dAscii = c; // 65.0
double d = 3.14;
int n = (int)d; // 3,小数部分被截断
将字符串类型转换为对应的类型 注意:类型必须对应的
int x1 = int.Parse("123");
double pi = double.Parse("3.14");
bool flag = bool.Parse("true");
更加安全,支持多种类型之间的转换 可以处理 null 和其他类型的转换
int x2 = Convert.ToInt32("123");
double y = Convert.ToDouble("3.14");
bool b = Convert.ToBoolean("true");
//必选部分
try
{
//可能会发生异常的代码
string? input = Console.ReadLine();
int number = int.Parse(input ?? "0"); // 空输入时默认0
Console.WriteLine("你输入的数字是: " + number);
}
catch (Exception ex)
{
//处理异常的代码
Console.WriteLine(ex.Message);
}
//可选部分
finally
{
//无论是否发生异常都会执行的代码
Console.WriteLine("程序结束");
}
其余和C语言差不多,懒得写了