C#学习记录-1
前言开始打算学习C#来扩展自己的技能面了主要就记录一下自己的学习过程方便自己后续查找。1.命名空间命名空间Namespace的作用就好比 一个逻辑上的“分类容器”用来把功能相关的类Class、接口interface、结构struct、枚举enum、委托delegate等类型组织在一起并解决重名冲突同时能使代码结构一目了然。using System; // // 命名空间公司名.项目名.模块名 // namespace VisionMES.DeviceModule { // 1. 枚举 (Enum)定义设备状态 public enum DeviceStatus { Offline, Online, Alarm } // 2. 委托 (Delegate)定义事件回调签名 public delegate void StatusChangedHandler(string message); // 3. 接口 (Interface)定义设备必须实现的能力 public interface IDevice { string Name { get; } void Connect(); void Disconnect(); } // 4. 类 (Class)核心业务逻辑 public class PlcDevice : IDevice { public string Name { get; private set; } public DeviceStatus Status { get; private set; } // 事件基于委托 public event StatusChangedHandler OnStatusChanged; public PlcDevice(string name) { Name name; Status DeviceStatus.Offline; } public void Connect() { Status DeviceStatus.Online; OnStatusChanged?.Invoke(${Name} 已连接); } public void Disconnect() { Status DeviceStatus.Offline; OnStatusChanged?.Invoke(${Name} 已断开); } } // 5. 结构体 (Struct)轻量级数据载体 public struct TemperatureData { public string DeviceName; public double Value; public DateTime Time; public string GetDisplay() ${DeviceName}{Value}℃; } } // // 使用示例在 Program.cs 或窗体中 // class Program { static void Main() { // 引用命名空间 using VisionMES.DeviceModule; // 1. 创建设备实例类 PlcDevice plc new PlcDevice(PLC-01); plc.OnStatusChanged (msg) Console.WriteLine(msg); plc.Connect(); // 输出PLC-01 已连接 plc.Disconnect(); // 输出PLC-01 已断开 // 2. 使用结构体 TemperatureData temp new TemperatureData { DeviceName PLC-01, Value 85.5, Time DateTime.Now }; Console.WriteLine(temp.GetDisplay()); // 输出PLC-0185.5℃ // 3. 使用枚举 DeviceStatus status DeviceStatus.Online; Console.WriteLine($当前状态{status}); // 输出Online } }以上代码是DeepSeek帮我生成的。在使用时发现老是报警CS0006表示编译器找不到某个引用.dll文件。CS5001程序不包含适合入口点的静态“Main”方法。后面又把问题丢给DeepSeek发现如果是Windows应用程序必须确保有一个Program.cs且包含正确的Main方法。如果是类库就不需要后面改成类库就ok。2.变量类型主要分为值类型和引用类型。值类型存的是‘东西本身’引用类型存的是‘东西的地址门牌号’。关键区别存储位置值类型通常在栈上引用类型对象在堆上栈由操作系统自动分配和释放用于存放函数的参数值、局部变量等。堆由程序员手动分配和释放若不释放程序结束时由操作系统回收。栈的内存地址由高到低生长方向向下。堆的内存地址由低到高生长方向向上。。赋值行为值类型复制数据引用类型复制地址。生命周期值类型随作用域结束销毁引用类型依赖 GC。可空性值类型不可为null除非使用NullableT或?引用类型可为null。继承性值类型是密封的sealed不支持继承引用类型可继承和多态。类别属于值类型struct属于引用类型class最常见类型int,double,bool,char,decimalstring,object,dynamic自定义类型struct定义class定义集合与容器无数组int[]、ListT、DictionaryTKey,TValue特殊类型枚举enum、可空类型int?、DateTime接口interface、委托delegate、事件event整数类型byte、short、int、long存储整数值不同范围浮点类型float、double、decimal存储小数精度和范围不同字符与字符串char、string单个字符 / 文本字符串布尔类型booltrue/false日期时间DateTime日期和时间结构体struct自定义轻量级值类型枚举enum自定义一组命名常量数组int[]、string[]等固定长度的同类型集合集合ListT、DictionaryTKey, TValue动态长度的数据容器可空类型int?、bool?值类型允许为null对象基类object所有类型的基类动态类型dynamic运行时确定类型using System; using System.Collections.Generic; namespace VariableTypesDemo { // 1. 定义枚举 (Enum) public enum DeviceStatus { Offline, Online, Alarm } // 2. 定义结构体 (Struct) public struct TemperatureData { public string DeviceName; public double Value; public DateTime Time; public string GetDisplay() $[{Time:HH:mm:ss}] {DeviceName}: {Value}℃; } // 3. 定义类 (Class) - 引用类型 public class Device { public string Name { get; set; } public DeviceStatus Status { get; set; } public Device(string name) { Name name; Status DeviceStatus.Offline; } public void ShowInfo() { Console.WriteLine($设备{Name}状态{Status}); } } class Program { static void Main(string[] args) { Console.WriteLine( C# 常用变量类型示例 \n); // // 1. 值类型 (Value Types) // // 1.1 整数类型 byte byteVar 255; // 0 ~ 255 short shortVar -32768; // -32768 ~ 32767 int intVar 100000; // 最常用 long longVar 9999999999L; // 长整数L 后缀 Console.WriteLine(【整数类型】); Console.WriteLine($ byte : {byteVar}); Console.WriteLine($ short : {shortVar}); Console.WriteLine($ int : {intVar}); Console.WriteLine($ long : {longVar}\n); // 1.2 浮点类型 float floatVar 3.14f; // 单精度f 后缀 double doubleVar 3.1415926535; // 双精度默认 decimal decimalVar 123.45m; // 高精度适合财务m 后缀 Console.WriteLine(【浮点类型】); Console.WriteLine($ float : {floatVar}); Console.WriteLine($ double : {doubleVar}); Console.WriteLine($ decimal: {decimalVar}\n); // 1.3 字符类型 char charVar A; Console.WriteLine(【字符类型】); Console.WriteLine($ char : {charVar}\n); // 1.4 布尔类型 bool isOnline true; bool isDebug false; Console.WriteLine(【布尔类型】); Console.WriteLine($ isOnline : {isOnline}); Console.WriteLine($ isDebug : {isDebug}\n); // 1.5 日期时间 DateTime now DateTime.Now; DateTime specificDate new DateTime(2025, 12, 31, 23, 59, 59); Console.WriteLine(【日期时间】); Console.WriteLine($ 当前时间 : {now}); Console.WriteLine($ 指定时间 : {specificDate}\n); // 1.6 枚举 DeviceStatus status DeviceStatus.Online; Console.WriteLine(【枚举】); Console.WriteLine($ 设备状态 : {status}\n); // 1.7 结构体 TemperatureData temp new TemperatureData { DeviceName PLC-01, Value 85.5, Time DateTime.Now }; Console.WriteLine(【结构体】); Console.WriteLine($ 温度数据 : {temp.GetDisplay()}\n); // // 2. 引用类型 (Reference Types) // // 2.1 字符串 string name 工业MES系统; string emptyString string.Empty; string nullString null; Console.WriteLine(【字符串】); Console.WriteLine($ 名称 : {name}); Console.WriteLine($ 空字符串 : {emptyString}); Console.WriteLine($ null字符串 : {(nullString null ? null : 有值)}\n); // 2.2 对象类型所有类型的基类 object objInt 100; object objStr Hello; object objBool true; Console.WriteLine(【object 类型】); Console.WriteLine($ 装箱 int : {objInt}); Console.WriteLine($ 装箱 string: {objStr}); Console.WriteLine($ 装箱 bool : {objBool}\n); // 2.3 数组固定长度 int[] numbers { 10, 20, 30, 40, 50 }; string[] names { 张三, 李四, 王五 }; Console.WriteLine(【数组】); Console.WriteLine($ int数组 : {string.Join(, , numbers)}); Console.WriteLine($ string数组 : {string.Join(, , names)}\n); // 2.4 集合动态长度 Liststring deviceList new Liststring { PLC-01, PLC-02, PLC-03 }; deviceList.Add(PLC-04); Dictionaryint, string idToName new Dictionaryint, string { { 1, 张三 }, { 2, 李四 } }; idToName[3] 王五; Console.WriteLine(【集合】); Console.WriteLine($ List : {string.Join(, , deviceList)}); Console.WriteLine($ Dictionary: ); foreach (var kvp in idToName) { Console.WriteLine($ ID {kvp.Key} → {kvp.Value}); } Console.WriteLine(); // 2.5 自定义类引用类型 Device device new Device(PLC-05); device.Status DeviceStatus.Online; Console.WriteLine(【自定义类】); device.ShowInfo(); Console.WriteLine(); // 2.6 可空类型值类型允许为 null int? nullableInt null; bool? nullableBool true; Console.WriteLine(【可空类型】); Console.WriteLine($ int? : {(nullableInt.HasValue ? nullableInt.Value.ToString() : null)}); Console.WriteLine($ bool? : {(nullableBool.HasValue ? nullableBool.Value.ToString() : null)}\n); // 2.7 动态类型运行时确定 dynamic dynValue 123; Console.WriteLine($ dynamic : {dynValue}); dynValue 现在变成了字符串; Console.WriteLine($ dynamic : {dynValue}\n); Console.WriteLine(按任意键退出...); Console.ReadKey(); } } }3.类型转换隐式类型转换数据小的类型往大的类型转换自动转换无需人为操作。int intNum 100; double doubleNum intNum; // 自动转int 转 double 不会丢精度 long longNum intNum; // 自动转int 转 long 不会丢范围显示类型转换即强制类型转换将大的数据类型转换成小的数据类型需人为转换。写(目标类型)进行强制转换。double doubleNum 3.14; int intNum (int)doubleNum; // 强制截断结果为 3小数部分丢失 long longNum 10000000000L; int intNum2 (int)longNum; // 危险如果值超出 int 范围会溢出不报错但结果错乱ConvertSystem.Convert类是.NET框架提供的一种便利工具允许开发者将一种基本数据类型转换为另一种基本数据类型。// 字符串转数字最常用 string str 123; int num Convert.ToInt32(str); // 成功 - 123 string str2 123.45; double d Convert.ToDouble(str2); // 成功 - 123.45 // 数字转字符串 string str3 Convert.ToString(456); // 456 // 日期时间转换 string dateStr 2026-08-31; DateTime date Convert.ToDateTime(dateStr); // 布尔转换 string boolStr true; bool flag Convert.ToBoolean(boolStr); // trueParse/Tryparse: 专门用于 将字符串转换为数值或日期。TryParse 是“不会抛异常”的版本强烈推荐用于用户输入场景。// Parse失败会抛异常 string input abc; int num1 int.Parse(input); // ❌ 抛出 FormatException程序崩溃 // TryParse推荐安全 string input2 123; if (int.TryParse(input2, out int result)) { Console.WriteLine($转换成功{result}); } else { Console.WriteLine(输入不是有效的数字); } // 日期 TryParse string dateInput 2026-08-31; if (DateTime.TryParse(dateInput, out DateTime dateResult)) { Console.WriteLine($日期{dateResult}); }