当前位置: 首页 > news >正文

C# 基础入门指南:从零开始学习 C# 编程

一、什么是 C#?

C#(读作 "C Sharp")是微软开发的一种面向对象类型安全的编程语言,运行在 .NET 框架之上。它结合了 C/C++ 的强大功能和 Java 的简洁性,广泛应用于:

  • 桌面应用开发(WinForms、WPF)
  • Web 应用开发(ASP.NET)
  • 游戏开发(Unity 引擎)
  • 移动开发(Xamarin)
  • 云服务和微服务

二、开发环境搭建

安装 .NET SDK

  1. 下载并安装最新版本的 .NET SDK
  2. 打开命令行(CMD 或 PowerShell),输入以下命令验证安装:
dotnet --version

如果显示版本号,说明安装成功。

选择 IDE

IDE适用场景价格
Visual Studio企业级开发,功能最全社区版免费
Visual Studio Code轻量级开发,跨平台免费
JetBrains Rider专业 .NET 开发付费

三、你的第一个 C# 程序

创建项目

打开终端,执行以下命令:

dotnet new console -n HelloWorld cd HelloWorld

编写代码

打开Program.cs文件,写入以下代码:

using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); Console.WriteLine("欢迎学习 C# 编程!"); } } }

运行程序

dotnet run

输出结果:

Hello, World! 欢迎学习 C# 编程!

四、C# 基础语法

1. 变量与数据类型

C# 是强类型语言,声明变量时必须指定类型。

// 值类型 int age = 25; // 整数 double price = 19.99; // 双精度浮点数 float pi = 3.14f; // 单精度浮点数 decimal salary = 5000.00m; // 高精度十进制数 char grade = 'A'; // 字符 bool isActive = true; // 布尔值 // 引用类型 string name = "张三"; // 字符串 object obj = "任何类型"; // 所有类型的基类

2. 类型推断 - var 关键字

var message = "Hello"; // 编译器自动推断为 string var count = 100; // 编译器自动推断为 int

3. 常量

const double PI = 3.14159; const string AppName = "我的应用";

4. 字符串操作

string firstName = "张"; string lastName = "三"; // 字符串拼接 string fullName = firstName + lastName; // 字符串插值(推荐) string greeting = $"你好,{fullName}!"; // 字符串方法 string text = " Hello World "; Console.WriteLine(text.Length); // 输出长度 Console.WriteLine(text.Trim()); // 去除首尾空格 Console.WriteLine(text.ToUpper()); // 转大写 Console.WriteLine(text.Replace("World", "C#")); // 替换

五、控制流语句

if-else 条件判断

int score = 85; if (score >= 90) { Console.WriteLine("优秀"); } else if (score >= 80) { Console.WriteLine("良好"); } else if (score >= 60) { Console.WriteLine("及格"); } else { Console.WriteLine("不及格"); }

switch 语句

string day = "周一"; switch (day) { case "周一": Console.WriteLine("新的一周开始"); break; case "周五": Console.WriteLine("即将周末"); break; case "周六": case "周日": Console.WriteLine("周末愉快"); break; default: Console.WriteLine("工作日"); break; }

循环语句

// for 循环 for (int i = 0; i < 5; i++) { Console.WriteLine($"第 {i + 1} 次循环"); } // foreach 循环 string[] fruits = { "苹果", "香蕉", "橙子" }; foreach (string fruit in fruits) { Console.WriteLine(fruit); } // while 循环 int count = 0; while (count < 3) { Console.WriteLine($"计数: {count}"); count++; }

六、数组与集合

数组

// 声明并初始化数组 int[] numbers = { 1, 2, 3, 4, 5 }; string[] names = new string[3] { "Tom", "Jerry", "Spike" }; // 访问数组元素 Console.WriteLine(numbers[0]); // 输出 1 Console.WriteLine(names[1]); // 输出 Jerry // 数组长度 Console.WriteLine($"数组长度: {numbers.Length}");

List 集合

using System.Collections.Generic; // 创建 List List<string> cities = new List<string>(); cities.Add("北京"); cities.Add("上海"); cities.Add("广州"); // 遍历 List foreach (string city in cities) { Console.WriteLine(city); } // List 常用方法 Console.WriteLine(cities.Count); // 元素个数 cities.Remove("上海"); // 删除元素 cities.Contains("北京"); // 是否包含

七、方法(函数)

// 定义方法 static int Add(int a, int b) { return a + b; } // 带默认参数的方法 static void Greet(string name, string greeting = "你好") { Console.WriteLine($"{greeting},{name}!"); } // 调用方法 int sum = Add(10, 20); Console.WriteLine($"10 + 20 = {sum}"); Greet("小明"); // 输出:你好,小明! Greet("小明", "早上好"); // 输出:早上好,小明!

八、面向对象编程基础

类与对象

// 定义一个类 public class Person { // 属性 public string Name { get; set; } public int Age { get; set; } // 构造函数 public Person(string name, int age) { Name = name; Age = age; } // 方法 public void Introduce() { Console.WriteLine($"我叫 {Name},今年 {Age} 岁。"); } } // 创建对象并使用 Person person = new Person("小李", 25); person.Introduce();

继承

// 基类 public class Animal { public string Name { get; set; } public virtual void MakeSound() { Console.WriteLine("动物发出声音"); } } // 派生类 public class Dog : Animal { public override void MakeSound() { Console.WriteLine("汪汪!"); } } // 使用继承 Dog dog = new Dog(); dog.Name = "旺财"; dog.MakeSound(); // 输出:汪汪!

九、异常处理

try { int[] arr = { 1, 2, 10 }; int result = arr[5]; // 会引发异常 } catch (IndexOutOfBoundsException ex) { Console.WriteLine($"数组越界:{ex.Message}"); } catch (Exception ex) { Console.WriteLine($"发生错误:{ex.Message}"); } finally { Console.WriteLine("无论是否出错都会执行"); }

十、实战小练习:简易计算器

using System; class Calculator { static void Main(string[] args) { Console.WriteLine("=== 简易计算器 ==="); Console.Write("请输入第一个数字:"); double num1 = Convert.ToDouble(Console.ReadLine()); Console.Write("请输入运算符(+、-、*、/):"); string op = Console.ReadLine(); Console.Write("请输入第二个数字:"); double num2 = Convert.ToDouble(Console.ReadLine()); double result = 0; switch (op) { case "+": result = num1 + num2; break; case "-": result = num1 - num2; break; case "*": result = num1 * num2; break; case "/": if (num2 != 0) { result = num1 / num2; } else { Console.WriteLine("除数不能为 0"); return; } break; default: Console.WriteLine("无效的运算符"); return; } Console.WriteLine($"结果:{num1} {op} {num2} = {result}"); } }

总结

本文介绍了 C# 的核心基础知识:

知识点说明
变量和数据类型掌握值类型和引用类型
控制流if、switch、循环
数组和集合List、数组的使用
面向对象类、继承、多态
异常处理try-catch 机制
http://www.jsqmd.com/news/1132424/

相关文章:

  • XCA开源证书管理:如何用现代工具解决传统PKI难题
  • 【译】组织好你的Asp.Net MVC解决方案
  • 实战指南:如何将微信聊天记录转化为个人AI训练数据资产
  • NHibernate Issues之1255:联合主键(composite-id)
  • 该如何进行WPF界面设计
  • o1-preview在机器学习项目中的协同建模实战
  • 6款主流AI智能降重工具 降痕效果拉满
  • Claude Code Review实战:AI驱动的自动化代码审查部署与优化指南
  • 【Bug已解决】Claude Team Plan 购买席位报错 Payment failed 解决方案
  • 从 Demo 到可上线:一个游戏智能客服 RAG 系统的工程化拆解
  • 修改网口MTU说明
  • Claude Fable 5 实战方法论 | 八招解锁 Agentic Coding 最高效率
  • 推荐几个好用到哭的小清新APP
  • 再次探讨企业级开发中的Try......Catch性能问题
  • 2025年CSDN年度技术趋势预测:AI、云原生与开发者工具的未来
  • 想找靠谱的商用轨道插座源头厂家?这些实用挑选方法一定要收好
  • BetterNCM安装器:让网易云音乐插件安装变得像点外卖一样简单
  • day0203
  • RTL8723DU WiFi+蓝牙驱动移植对比:全志D1与Milk-V Duo 2平台实战解析
  • MSF 反弹 Shell 实战教程:从生成木马到获取服务器权限
  • 数据视图学习博客笔记(含数据表对比)
  • 5个VADER情感分析技巧:社交媒体情感分析终极指南
  • 01-PEFT源码阅读-项目总览与设计理念
  • dbus的如何使用教程以及相关概念
  • 酷哇科技递表:从无人环卫成长起来的具身独角兽
  • Redis——分布式锁
  • 【windows】安装MiMoCode并使用
  • 计组面试--h自用
  • Lua--协同线程与文件IO
  • 小红书博主都在偷偷用的AI工具,不用懂代码就能自动运营