52 - C# 入门教程

适用人群:游戏开发、企业应用开发兴趣
难度:中等
预计学习时间:40-50小时

为什么学 C#?

优势说明
Unity引擎游戏开发首选语言(Unity用C#)
.NET生态微软强大生态,企业级支持
跨平台.NET 8支持Windows/Linux/macOS
语法现代LINQ、async/await、模式匹配
就业游戏开发、企业应用需求大

学习路线

第1阶段:基础语法(2周)
├── 变量与类型(int/string/bool/double)
├── 控制流(if/switch/for/while)
├── 方法(函数)
├── 数组与集合(List/Dictionary)
├── 字符串操作
└── 异常处理(try/catch)

第2阶段:面向对象(2周)
├── 类与对象
├── 继承与多态
├── 接口(Interface)
├── 抽象类
├── 属性与索引器
└── 静态类与扩展方法

第3阶段:高级特性(2周)
├── LINQ查询
├── 泛型
├── 委托与事件
├── async/await异步编程
├── 反射与特性
└── 模式匹配

第4阶段:实战方向(3周)
├── ASP.NET Core Web API
├── Entity Framework Core(ORM)
├── Unity游戏开发
└── Blazor前端框架


基础语法速查

using System;
using System.Collections.Generic;
using System.Linq;

// 变量
int age = 25;
string name = "Alice";
double price = 9.99;
bool isActive = true;
var list = new List<int> { 1, 2, 3 };  // 类型推断

// 字符串
string greeting = $"Hello, {name}! You are {age} years old.";
string multiLine = @"Line 1
Line 2
Line 3";

// 方法
static int Add(int a, int b) => a + b;  // 表达式体
static void PrintInfo(string name, int age = 18)  // 默认参数
{
    Console.WriteLine($"{name}, {age}");
}

// 类
class Person
{
    public string Name { get; set; }    // 属性
    public int Age { get; private set; } // 只读setter
    
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    
    public virtual string Introduce() => $"I'm {Name}, {Age} years old.";
}

class Student : Person  // 继承
{
    public string School { get; set; }
    
    public Student(string name, int age, string school) : base(name, age)
    {
        School = school;
    }
    
    public override string Introduce() => $"I'm {Name}, studying at {School}.";
}

// 接口
interface IPlayable
{
    void Play();
    string Status { get; }
}

class Music : IPlayable
{
    public string Title { get; set; }
    public string Status { get; private set; } = "Stopped";
    
    public void Play()
    {
        Status = "Playing";
        Console.WriteLine($"Now playing: {Title}");
    }
}

// LINQ查询
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var evens = numbers.Where(n => n % 2 == 0).ToList();
var sum = numbers.Sum();
var avg = numbers.Average();
var sorted = numbers.OrderByDescending(n => n).ToList();

var people = new List<Person>
{
    new Person("Alice", 25),
    new Person("Bob", 30),
    new Person("Charlie", 20)
};

var adults = people.Where(p => p.Age >= 25)
                   .OrderBy(p => p.Name)
                   .Select(p => new { p.Name, p.Age })
                   .ToList();

// async/await
static async Task<string> FetchDataAsync(string url)
{
    using var client = new HttpClient();
    var response = await client.GetStringAsync(url);
    return response;
}

// 泛型
class Repository<T> where T : class
{
    private readonly List<T> _items = new();
    
    public void Add(T item) => _items.Add(item);
    public T GetById(int index) => _items[index];
    public IEnumerable<T> GetAll() => _items;
}

// 模式匹配
static string Describe(object obj) => obj switch
{
    int i when i > 0 => "Positive integer",
    int i when i < 0 => "Negative integer",
    0 => "Zero",
    string s when s.Length > 10 => "Long string",
    string s => $"String: {s}",
    null => "Null",
    _ => "Unknown"
};


ASP.NET Core Web API 快速上手

// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.MapControllers();
app.Run();

// Controllers/TodoController.cs
[ApiController]
[Route("api/[controller]")]
public class TodoController : ControllerBase
{
    private static readonly List<TodoItem> _todos = new();
    
    [HttpGet]
    public ActionResult<IEnumerable<TodoItem>> GetAll() => Ok(_todos);
    
    [HttpPost]
    public ActionResult<TodoItem> Create(TodoItem item)
    {
        item.Id = _todos.Count + 1;
        _todos.Add(item);
        return CreatedAtAction(nameof(GetAll), new { id = item.Id }, item);
    }
    
    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        var item = _todos.FirstOrDefault(t => t.Id == id);
        if (item == null) return NotFound();
        _todos.Remove(item);
        return NoContent();
    }
}


推荐资源

资源说明
Microsoft Learn官方免费教程
C# Yellow Book免费电子书
Unity LearnUnity游戏开发
Entity Framework Core教程数据库ORM

实战项目建议

  1. Todo API:ASP.NET Core CRUD接口
  2. Unity 2D游戏:入门游戏开发
  3. WPF桌面应用:Windows桌面开发
  4. Blazor Web应用:用C#写前端
返回首页