cs文件结构
using WinFormsApp1.Common; //引用命名空间
namespace WinFormsApp1.Models //项目命名空间
public static class Program //类名称
{
public static void Main(string[] args) //方法或者函数
{
//大括号内部即为方法体,用于写具体方法
}
}
注释
/* 多行注释 */
//
///文档注释
//文档注释方法只能在类、方法、属性上使用
/// <summary>
/// 这是说你好的方法
/// </summary>
/// <param name="i">一个数字</param>
void SayHello(int i)
{
//写具体方法
Helper;
}
变量
- 变量是一个供程序存储数据盒子。在C#中,每个变量都有一个特定的类型,不同类型的变量其内存大小也不同。
c#中的基本类型大致分以下几类
| 类型 | 举例 |
|---|---|
| 整数类型 | byte(8位 0-255)、short(16位)、int(32位)、long(64位) |
| 浮点型 | float(小数类型)、double(双精度) |
| 十进制类型 | decimal |
| 布尔类型 | bool |
| 字符类型 | strig、char |
| 空类型 | null |
//整数类型
//byte没有负数
byte bMax = byte.MaxValue; //byte没有负数
byte bMin = byte.MinValue;
short sMax = short.MaxValue;
short sMin = short.MinValue;
int iMax = int.MaxValue;
int iMin = int.MinValue;
long lMax = long.MaxValue;
long lMin = long.MinValue;
short s = 0;
int i = 0;
i = s; //范围小的可以放到范围大的
//s = i; //范围大的不可以放到范围小的,会报错
float f = 1.1f;
f = s;
f = i;
f = lMax;
//lMax = f;
double d = 1.1;
d = f;
decimal dc = 1.1m;
string str = "hello";
char c = 'H'; //只能接收一个字符,并且是单引号
string name = "Tom";
string str = $"Hi,{name}";
switch简化
string res = number switch
{
"101" => "101",
"102" => "102",
"103" => "103",
_ => "101",
}
数组
//声明没有元素的数组
int[] ints = new int[6];
//声明初始化有元素的数组
int[] ints = new int[]{1,2,3,4};
//简化声明
int[] ints = {1,2,3};
转换
//(int)显示强制转换
(int)5.21 //5 只截取整数部分
//Parse把string类型转换成int、char、double...
int.Parse("5"); //5 将string类型转换成int,括号中一定是string类型
Convert.ToInt32(4.3); //4 四舍六入五保双
//Convert.ToInt32(null); //0
//int.Parse(null); //异常
函数
//void 无返回值
public void Add(int a, int b){
int total = a + b;
}
//函数返回值
public int Add(int a, int b){
int total = a + b;
return total;
}
参数修饰符
//out 输出参数由被调用的方法赋值,因此按引用传递,如果被调用的方法没有给输出参数赋值,就会出现编译错误。out最大的用途就是调用者只使用一次方法的调用就能获得多个返回值。
Sub(2,1,out int res)
Message.show(res.Tostring()); //3
void Sub(int num1, int num2, out int res)
{
res = num1 + num2;
}
//ref调用者赋初值,并且可以由被调用的方法可选的重新赋值。
var res = Add(2,1); //3
int Add(params int[] ints){
int res = ints[0] + ints[1];
return res;
}
out和ref的区别
- out修饰的参数必须在方法内修改,而ref可以修改也可以不修改。
- out在传入参数的时候,参数是局部变量,可以不用赋值,因为out一定会对其进行赋值。
- ref修饰的参数,在实参必须有初始值才能调用。ref修饰的不一定会给它赋值。