ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

Linux.NET学习手记(2)

Linux.NET学习手记(2) Linux.NET学习手记2在上一篇手记中我们完成了Linux环境下.NET开发环境的搭建并成功运行了第一个Hello World程序。今天我们将正式进入C#语言的核心语法世界从最基础的变量与数据类型开始逐步深入到面向对象编程的实战应用。请系好安全带我们开始加速。### 变量与数据类型程序的血肉任何编程语言的第一课都是从变量开始。在C#中变量就像是一个个标注了类型的容器编译器会严格检查你往里面放的东西是否符合规范。这种强类型特性虽然初学时觉得繁琐但长期来看能避免大量运行时错误。基础数据类型全家福| 类型 | 说明 | 示例 ||------|------|------|| int | 32位整数 |int age 25;|| long | 64位整数 |long big 100000L;|| float | 单精度浮点 |float pi 3.14f;|| double | 双精度浮点 |double d 3.14159;|| decimal | 高精度十进制 |decimal price 19.99m;|| bool | 布尔值 |bool isOK true;|| string | 字符串 |string name Linux;|| char | 单个字符 |char grade A;|变量声明的两种风格csharp// 传统方式先声明后赋值int score;score 98;// 现代方式类型推断C# 3.0var temperature 36.5; // 自动推断为doublevar message Hello .NET on Linux; // 自动推断为string### 控制流让程序学会思考一个只会顺序执行的程序是没有灵魂的。通过条件判断和循环我们可以让程序根据不同的情况做出不同的反应。这就像给程序装上了神经系统。if-else 分支判断实战csharpusing System;class Program{ static void Main() { // 模拟一个简单的成绩评级系统 Console.Write(请输入考试成绩0-100); string input Console.ReadLine(); int score int.Parse(input); // 多分支条件判断 if (score 90 score 100) { Console.WriteLine(优秀继续保持); } else if (score 80 score 90) { Console.WriteLine(良好还有提升空间。); } else if (score 60 score 80) { Console.WriteLine(及格需要加倍努力。); } else if (score 0 score 60) { Console.WriteLine(不及格建议重新学习相关章节。); } else { Console.WriteLine(输入无效请输入0-100之间的数字。); } }}循环结构三兄弟-for循环适合已知循环次数-while循环适合条件未知但需要持续判断-foreach循环专门遍历集合csharpusing System;using System.Collections.Generic;class LoopDemo{ static void Main() { // for循环打印1到10的平方 Console.WriteLine( 1到10的平方 ); for (int i 1; i 10; i) { Console.WriteLine(${i}² {i * i}); } // while循环模拟用户登录重试 Console.WriteLine(\n 登录验证 ); string password ; int attempts 0; while (password ! linux123 attempts 3) { Console.Write(请输入密码); password Console.ReadLine(); attempts; if (password ! linux123 attempts 3) { Console.WriteLine($密码错误还剩{3 - attempts}次机会。); } } if (password linux123) Console.WriteLine(登录成功欢迎使用Linux.NET系统。); else Console.WriteLine(登录失败账户已锁定。); // foreach循环遍历数组 Console.WriteLine(\n 遍历水果列表 ); Liststring fruits new Liststring { 苹果, 香蕉, 橙子, 葡萄 }; foreach (string fruit in fruits) { Console.WriteLine($我喜欢吃{fruit}); } }}### 方法代码复用的艺术当程序逻辑越来越复杂把重复代码提取成方法就变得至关重要。方法就像是一个个功能模块可以被反复调用让代码结构清晰且易于维护。方法定义与调用示例csharpusing System;class MethodDemo{ // 无返回值方法 static void PrintWelcome(string userName) { Console.WriteLine($欢迎您{userName}); } // 有返回值方法 static double CalculateArea(double radius) { return Math.PI * radius * radius; } // 带默认参数的方法C# 4.0 static void ShowMessage(string message, string prefix 提示) { Console.WriteLine(${prefix}{message}); } static void Main() { // 调用无返回值方法 PrintWelcome(张三); // 调用有返回值方法 double area CalculateArea(5.0); Console.WriteLine($半径为5的圆面积是{area:F2}); // 调用带默认参数的方法 ShowMessage(文件保存成功); ShowMessage(内存不足, 警告); }}### 面向对象编程构建模块化世界面向对象编程OOP是C#的核心思想。想象一下你要开发一个学生管理系统如果用传统方式你会写一堆散乱的函数。但如果用OOP你可以把学生抽象成一个类包含属性姓名、年龄、成绩和行为学习、考试、休息这样代码的组织性和复用性会大大提升。一个完整的类设计实例csharpusing System;using System.Collections.Generic;// 定义学生类public class Student{ // 属性封装 public string Name { get; set; } public int Age { get; set; } private Listdouble _scores new Listdouble(); // 只读属性 public double AverageScore { get { if (_scores.Count 0) return 0; double sum 0; foreach (var score in _scores) { sum score; } return sum / _scores.Count; } } // 构造函数 public Student(string name, int age) { Name name; Age age; } // 方法添加成绩 public void AddScore(double score) { if (score 0 score 100) { _scores.Add(score); Console.WriteLine(${Name}添加成绩{score}成功。); } else { Console.WriteLine(成绩必须在0-100之间); } } // 方法显示信息 public void DisplayInfo() { Console.WriteLine($姓名{Name}年龄{Age}平均分{AverageScore:F1}); }}// 继承示例public class GraduateStudent : Student{ public string ResearchTopic { get; set; } public GraduateStudent(string name, int age, string topic) : base(name, age) { ResearchTopic topic; } public void DisplayResearch() { Console.WriteLine(${Name}的研究方向是{ResearchTopic}); }}class Program{ static void Main() { // 创建学生对象 Student student1 new Student(李四, 20); student1.AddScore(85); student1.AddScore(92); student1.AddScore(78); student1.DisplayInfo(); // 创建研究生对象继承 GraduateStudent grad new GraduateStudent(王五, 24, 人工智能与机器学习); grad.AddScore(95); grad.DisplayInfo(); grad.DisplayResearch(); }}### 异常处理让程序更健壮在Linux环境下运行.NET程序文件操作、网络请求等都可能抛出异常。如果不处理程序会直接崩溃。通过try-catch结构我们可以优雅地处理这些意外情况。csharpusing System;using System.IO;class ExceptionDemo{ static void Main() { try { Console.Write(请输入文件路径); string path Console.ReadLine(); // 尝试读取文件 string content File.ReadAllText(path); Console.WriteLine(文件内容如下); Console.WriteLine(content); } catch (FileNotFoundException) { Console.WriteLine(错误文件不存在请检查路径是否正确。); } catch (UnauthorizedAccessException) { Console.WriteLine(错误没有权限读取该文件); } catch (Exception ex) { // 捕获所有其他异常 Console.WriteLine($发生未知错误{ex.Message}); } finally { Console.WriteLine(程序执行完毕资源已释放。); } }}### 总结通过本篇手记的学习我们已经掌握了C#语言的几个核心支柱1.变量与类型系统理解了强类型语言的优势学会了使用var进行类型推断2.控制流掌握了if-else、for、while、foreach等关键控制结构3.方法学会了如何封装代码逻辑提高复用性4.面向对象理解了类、对象、属性、方法、继承等OOP核心概念5.异常处理学会了如何让程序在错误面前保持稳定在Linux环境下这些知识同样完全适用。因为.NET Core/.NET 5是跨平台的你写的每一行C#代码无论在Windows、Linux还是macOS上运行行为都完全一致。这就是现代.NET框架的魅力所在。下一期我们将深入探讨LINQ语言集成查询、异步编程和文件操作等进阶主题。这些内容将帮助你构建更强大、更高效的Linux.NET应用程序。请保持练习我们下次见
返回列表