# C-sharp **Repository Path**: swordying/c-sharp ## Basic Information - **Project Name**: C-sharp - **Description**: # C#学习笔记 - **Primary Language**: C# - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 3 - **Forks**: 0 - **Created**: 2022-12-05 - **Last Updated**: 2023-03-11 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # C# 学习笔记 ## 1、基本简介 - C# 读作 "See Sharp" 1. 定义:一个简单的、安全的、通用的、面向对象的编程语言 2. 作者:微软公司(Microsoft)安德斯·海尔斯伯格(Anders Hejlsberg) 3. 发布时间:2000年6月 4. 设计目的:专为公共语言基础结构(CLI)设计 5. 文件扩展名: ` .cs ` ## 2、语言特容易学习性 1. 简单安全 2. 跨平台 3. 面向对象 4. 面向组件 5. 结构化语言 6. 高效率 ## 3、应用场景 1. 网站开发 2. 电脑应用以及手机应用等终端开发 3. 工具类等服务器开发 4. 开发 Unity3D 应用的脚本语言 ## 4、安装方法 MacOS 1. Visual Studio for Mac https://visualstudio.microsoft.com/zh-hans/downloads 2. IDE 集成 .NET Framework ## 5、代码注释 ```c# // 单行注释 /* 多行注释 */ /// 可被编译的注释,用于生成程序文档 ``` ## 6、C# 程序最小结构 - C# 文件的后缀为 ` .cs ` 1. 引入的公共类 2. 命名空间声明(Namespace declaration) 3. 一个 class 4. 一个 静态的 Main 方法 5. 语句(Statements)& 表达式(Expressions) ```C# // 1. 引入的公共类 using System; // 2. 命名空间声明(Namespace declaration) namespace First { // 3. 一个 class class First { // 4. 一个 静态的 Main 方法 static void Main() { // 5. 语句(Statements)& 表达式(Expressions) Console.WriteLine("Hello World! My name is C#."); } } } ``` ## 7、数据结构 ### 1. 布尔值 bool 1. True 2. False (默认) ### 2. 数值 number 序号|类型|简介|长度|默认值 --|:--|:--|:--|--: 1|byte|8 位无符号整数|0 到 255|0 2|decimal|128 位精确的十进制值|-|0.0M 3|double|64 位双精度浮点型|-|0.0D 4|float|32 位单精度浮点型|-|0.0F 5|int|32 位有符号整数类型|-|0 6|long|64 位有符号整数类型|-|0L 7|sbyte|8 位有符号整数类型|-128 到 127|0 8|short|16 位有符号整数类型|-32,768 到 32,767|0 9|uint|32 位无符号整数类型|-|0 10|ulong|64 位无符号整数类型|-|0 11|ushort|16 位无符号整数类型|0 到 65,535|0 ### 3. 字符串 string 1. ` string ` 关键字是 ` System.String ` 类的别名 2. 声明字符串变量 ```C# string str = "字符串声明方式"; ``` 3. 连接字符串 ```C# string s1 = "a"; string s2 = "b"; string s12 = s1 + s2; Console.WriteLine(s12); // ab ``` 4. 字符串属性 1. 字符串 ` .Length ` 获取字符串的长度 5. 字符串方法 1. ` String.Join("连接符号",数组); ` ```C# string[] s = { "a", "b", "c" }; string str =String.Join(",",s); Console.WriteLine(str); // a,b,c ``` 2. ` String.Format(); ` 3. ` String.Concat(字符串1,字符串2,...); ` // 连接多个字符串 4. ` String.IsNullOrEmpty(字符串); ` ```C# string str = ""; // True //string str = "0"; // False //string str = "False"; // False //string str = "True"; // False //string str = null; // True bool b = string.IsNullOrEmpty(str); Console.WriteLine(b); // True ``` 5. ` String.IndexOf(); ` 6. ` String.LastIndexOf(); ` 7. ` String.Remove(); ` 8. ` 字符串.Split(); ` 9. ` 字符串.Replace("查找的字符串","用于替换的字符串"); ` // 返回值为新字符串 10. ` 字符串.ToLower(); ` // 返回转换为小写后的字符串 11. ` 字符串.ToUpper(); ` // 返回转换为大写后的字符串 12. ` 字符串.Trim(); ` // 返回移除当前字符串首尾的空白字符后的字符串 包括 空格、换行符、制表符 ### 4. 数组 array - 定义方法:` = {1,2,3} ` - 备注:数组之间赋值自动为引用传递 1. 矩阵数组/多维数组 ``` int[,] i = { {1, 2, 3}, {4, 5, 6}, }; Console.WriteLine(i[1,1]); // 5 ``` 2. 交错数组 [交错数组是一维数组] ```C# int[][] i = { new int[] {1, 2, 3}, new int[] {4, 5, 6}, }; Console.WriteLine(i[0][1]); // 2 Console.WriteLine(i[1][1]); // 5 ``` 3. 数组的属性 1. .IsFixedSize 获取数组的固定大小 2. .IsReadOnly 获取数组是否可读 3. .Length 获取所有数组中的元素总数 4. .LongLength 获取所有数组中的元素总数 5. .Rank 获取数组的维度 4. 数组 Array 的方法 1. Array.Clear(array,index,length); 2. ` 数组.GetType(); ` 获取数组的实例类型 3. Array.Reverse(数组); 反转数组中元素的顺序 ### 5. 结构体 Struct - 概念:使用单一变量储存各种数据的一种数据结构 1. 定义结构体 ```C# struct Location { public int x; public int y; public string house_number; } ``` 2. 如何选择结构体和类 1. 如果要使用继承多态时,使用类 2. 如果是静态的数据集合,使用结构体 3. 如果不需要或者禁止值传递,使用结构体 ### 6. 对象 - 封装性:public>internal|protected>internal>protected>private 1. ` public ` 所有对象都可以访问 2. ` protected ` 只在本类以及子类中访问 3. ` private ` 只在本类中访问 4. ` internal ` 同一个程序集中可以访问 5. ` protected internal ` 在当前程序集或派生自包含类中使用 (protected 或 internal) - 语法实例 ```C# // 引用类 using System; // 命名空间 namespace First { class Apple { // 成员属性 公共:都可以访问 public string color = "红色"; // 成员属性 保护:本类以及子类可以访问 protected string from; // 成员属性 私有:只在本类中访问,不可继承 private string taste = "酸甜味"; // 成员属性 静态 public static string type = "树果"; // 成员方法 公共 public string getTaste() { return taste; } // 成员方法 保护 protected string getFrom() { return from; } // 成员方法 私有[默认] string getColor() { return this.color; } // 构造函数 public Apple(string _color = "", string taste = "") { color = _color; this.taste = taste; } public void index() { Console.WriteLine("apple-index"); } } class Show: Apple // : 继承关键符号 { // 程序入口方法 public static void Main(string[] args) { Apple iPhone = new Apple("象牙白", "手机味"); Console.WriteLine("苹果的颜色为:{0}\n苹果的味道为:{1}", iPhone.color, iPhone.getTaste()); // 访问静态属性 Console.WriteLine(Show.type); // 树果 // is 用于判断对象与类之间是否存在派生关系 Show MyShow = new Show(); bool is_apple = MyShow is Apple; Console.WriteLine(is_apple); // True } // 重写必须要加上 new 关键字 public new void index() { Console.WriteLine("show-index"); } } } ``` - 备注:C# 中没有直接的多继承策略,需要通过接口才能实现 ### 7. 空 null - ` ? ` 可以为 ` int `、` double `、` bool ` 等无法直接赋值为 null 的数据类型进行 null 赋值 ```C# int ? i = null; i = i ?? 0; // ?? 检测 null Console.WriteLine(i); // 0 ``` ### 8. 枚举 enum 1. 声明枚举: ```C# enum enum_name { value_1, value_2, }; class Test { static void Main() { int key = (int) enum_name.value_1; Console.WriteLine(key); } } ``` - 备注:枚举是独立于类的一种数据结构 ## 8、C# 的数据类型 ### 1. 值类型 1. 布尔值 bool 2. 数值 number 3. char ### 2. 引用类型 1. 对象 Object 2. 动态 Dynamic:可以存储任何类型的值在动态数据类型变量中 3. 字符串 String ### 3. 指针类型 1. 指针类型变量存储另一种类型的内存地址 ## 9、C# 类型转换 1. 隐式类型转换:不会造成数据丢失 2. 显式类型转换:相对造成数据丢失 序号|方法 & 描述|描述 --|--|-- 1|ToBoolean|如果可能的话,把类型转换为布尔型。 2|ToByte|把类型转换为字节类型。 3|ToChar|如果可能的话,把类型转换为单个 Unicode 字符类型。 4|ToDateTime|把类型(整数或字符串类型)转换为 日期-时间 结构。 5|ToDecimal|把浮点型或整数类型转换为十进制类型。 6|ToDouble|把类型转换为双精度浮点型。 7|ToInt16|把类型转换为 16 位整数类型。 8|ToInt32|把类型转换为 32 位整数类型。 9|ToInt64|把类型转换为 64 位整数类型。 10|ToSbyte|把类型转换为有符号字节类型。 11|ToSingle|把类型转换为小浮点数类型。 12|ToString|把类型转换为字符串类型。 13|ToType|把类型转换为指定类型。 14|ToUInt16|把类型转换为 16 位无符号整数类型。 15|ToUInt32|把类型转换为 32 位无符号整数类型。 16|ToUInt64|把类型转换为 64 位无符号整数类型。 ## 10、变量 ### 1. 定义变量 - 语法: ` = ` #### 1. 字符串的特殊字符的转译问题 ```C# String avaiable_simple = "换\n行"; Console.WriteLine(avaiable_simple); /* // 输出: 换 行 */ String avaiable_simple2 = @"换\n行"; Console.WriteLine(avaiable_simple2); // 输出:换\n行 ``` ### 2. 作用域 ### 3. 引用传递 - C# 中 使用 ref 作为引用传递关键字 1. 普通变量 ```C# string str = "string"; ref string s = ref str; Console.WriteLine(s); // string str = "str"; Console.WriteLine(s); // str ``` 2. 类方法 ` function_name(ref string _value) ` ## 11、常量 - 定义常量: ` const = ` ## 12、流程控制语句 ### 1. 判断 - 判断遵循短路原则 ```C# if(1==2){ Console.WriteLine("1==1"); }else if(2==2){ Console.WriteLine("2==2"); }else{ Console.WriteLine("x==x"); } ``` - 三元运算: ` Exp1 ? Exp2: Exp3 ` ```C# bool b = True; string a = (b == True) ? '真' : '假'; Console.WriteLine(string); // 真 ``` ### 2. 循环 #### 1、while 循环 ```C# int i = 1; while(i <= 10){ Console.WriteLine(i); i++; } ``` #### 2、for 循环 ```C# for(int i = 1;i<= 10;i++){ Console.WriteLine(i); } ``` #### 3、do...while 循环 ```C# int i = 1; do{ Console.WriteLine(i); i++; }while(i<=10); ``` #### 3、循环控制关键词 1. ` continue ` 跳过本次循环 2. ` break ` 终止本次循环 ```C# for (int i = 1; i <= 10; i++){ Console.WriteLine("i 运行次数:{0}", i); if (i == 2){ continue; } if (i == 5){ break; } Console.WriteLine("i={0}",i); } // 输出:i=1,3,4 // i 运行次数:5 ``` ```C# int j = 0; while (j < 10){ j++; Console.WriteLine("j 运行次数:{0}", j); if (j == 2){ continue; } if (j == 5){ break; } Console.WriteLine("j={0}",j); } // 输出:j=1,3,4 // j 运行次数:5 ``` ### 3. 迭代 ```C# int[] int_array = new int[]{1,2,3,4,5}; foreach(int value in int_array){ Console.WriteLine(value); } ``` ## 13、运算 ### 1. 算数运算符 - ` + - * / % ++ -- ` ### 2. 关系运算符 - ` == != > < >= <= ` ### 3. 逻辑运算法 - ` && || ! ` ### 4. 位运算符 - ` & | ^ ~ >> << ` ## 14、接口 Interface - 概念:接口的目的是定义参与编码的类所要遵循的规则 1. 接口定义了属性、方法 与 事件 2. 语法 ```C# using System; // 定义接口 interface IMyFirstInterface { // 默认封装为 public void show(); } // 实现接口 class FirstImplement: IMyFirstInterface { static void Main() { FirstImplement first_implement = new FirstImplement(); first_implement.show(); } // 需要重写接口所定义的方法 public void show() { Console.WriteLine("您实现了接口并重写其方法"); } } ``` ## 15、常见函数 ### 1. sizeof - 返回数据类型的大小 ### 2. typeof - 返回类 class 的类型 ### 3. 时间 1. 获取时间:` System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); // 2023-01-01 12:00:00 ` 2. 获取时间戳:` new System.DateTimeOffset(System.DateTime.Now).ToUnixTimeSeconds(); // 1675822215 ` ## 16、C# 中的正则表达式 ```C# // 类上引入 开始 using System; using System.Text.RegularExpressions; // 类上引入 结束 string s = "123456789"; string pattern = @"3(.*?)7"; System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(pattern); MatchCollection current_match = r.Matches(s); foreach (Match value in current_match) { Console.WriteLine(value); // 34567 } ``` ## 17、C# 中的异常处理 ```C# try{ // 需要检测异常的代码块 }catch(异常种类){ // 获取异常信息,同时可以使用 Throw 抛出异常类 }finally{ // 异常后所要执行的代码 } ``` ## 18、文件操作 - 文件操作类:File[Unity 的 WebGL 平台无效]、FileStream、StreamReader、StreamWriter 等 1. 新建 ```C# string file_path = "/Users/Downloads/test.cs"; FileStream f = new FileStream(file_path, FileMode.Append, FileAccess.Write); // FileMode.Append:如果存在就将光标放置在文件末尾,不存在就新建 // FileAccess.Write:使文件处于写操作状态 // 备注:请确认文件所在目录是否可写 ``` 2. 读取 ```C# string file_path = "./test.cs"; // 第一种:快读取 if(File.Exists(file_path)){ string fast_read_result = File.ReadAllText(file_path); Console.WriteLine(fast_read_result); }else{ Console.WriteLine("{0}文件不存在",file_path); } // 第二种:基于 FileStream using System.Text; string read_result = null; try{ FileStream fs = new FileStream(file_path, FileMode.Open); int n = (int)fs.Length; byte[] b = new byte[n]; int r = fs.Read(b, 0, n); fs.Close(); read_result = Encoding.UTF8.GetString(b, 0, n); }catch (IOException e){ Console.WriteLine("没有文件"); } Console.WriteLine(read_result); // 第三种:基于 StreamReader StreamReader sr = new StreamReader(file_path, Encoding.UTF8); string read_result = sr.ReadToEnd(); // 按行读取 string line; while( (line = sr.ReadLine()) != null ) { Console.WriteLine(line); } sr.Close(); Console.WriteLine(read_result); // 第四种:基于 FileStream、StreamReader FileStream fs = new FileStream(file_path, FileMode.Open); StreamReader sr = new StreamReader(fs, Encoding.UTF8); string read_result = sr.ReadToEnd(); fs.Close(); sr.Close(); Console.WriteLine(read_result); ``` 3. 写入 ```C# // 第一种:基于 File File.AppendAllText(file_path, "追加写入字符串"); File.WriteAllText(file_path, "覆盖写入字符串"); // 第二种:基于 StreamWrite // true 表示文件不存在则创建 using (StreamWriter sw = new StreamWriter(file_path, true)) { sw.WriteLine("写入换行"); // 写入换行 sw.Write("写入不换行"); // 写入不换行 sw.Close(); // 关闭资源 } // 第三种:FileStream 与 StreamWirte 结合 FileStream fs = new FileStream(file_path, FileMode.Append); using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine("写入换行"); // 写入换行 sw.Write("写入不换行"); // 写入不换行 sw.Close(); // 关闭资源 } ``` 4. 关闭 ```C# fs.Close(); sr.Close(); sw.Flush(); // 清空缓存区 sw.Close(); ``` 5. 删除 ```C# // 删除目录 string file_path = ""; if(Directory.Exists(file_path)){ Directory.Delete(file_path,true); // true 表示忽略目录中的文件 }else{ Console.WriteLine("此目录不存在"); } // 删除文件 string file_path = ""; if(File.Exists(file_path)){ File.Delete(file_path); }else{ Console.WriteLine("此文件不存在"); } ``` 6. 移动 ```C# File.move("文件 全路径","文件新 全路径"); ``` ## 附录其他 1. C# 官方文档 https://learn.microsoft.com/zh-cn/dotnet/csharp/ 2. C# 菜鸟教程 https://www.runoob.com/csharp/