1. .NET SDK 安装
1.1 下载和安装 .NET SDK
Windows 系统
# 使用 Chocolatey 安装(推荐)
choco install dotnet-sdk
# 或使用 winget 安装
winget install Microsoft.DotNet.SDK.8
# 验证安装
dotnet --version
dotnet --info
macOS 系统
# 使用 Homebrew 安装
brew install --cask dotnet-sdk
# 或下载安装包
# 访问 https://dotnet.microsoft.com/download
# 验证安装
dotnet --version
Linux 系统
# Ubuntu/Debian
wget https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
sudo apt-get update
sudo apt-get install -y dotnet-sdk-8.0
# CentOS/RHEL/Fedora
sudo dnf install dotnet-sdk-8.0
# Arch Linux
sudo pacman -S dotnet-sdk
# 验证安装
dotnet --version
1.2 .NET SDK 版本管理
# 查看已安装的 SDK 版本
dotnet --list-sdks
# 查看已安装的运行时版本
dotnet --list-runtimes
# 查看详细信息
dotnet --info
# 创建 global.json 文件指定 SDK 版本
echo '{
"sdk": {
"version": "8.0.100"
}
}' > global.json
2. 集成开发环境 (IDE)
2.1 Visual Studio 2022
安装和配置
# 下载 Visual Studio 2022
# 访问 https://visualstudio.microsoft.com/downloads/
# 推荐工作负载:
# - .NET 桌面开发
# - ASP.NET 和 Web 开发
# - .NET 跨平台开发
有用的扩展
{
"推荐扩展": [
"ReSharper",
"CodeMaid",
"Productivity Power Tools",
"GitHub Extension for Visual Studio",
"Live Share",
"IntelliCode"
]
}
Visual Studio 配置
// 代码样式配置 (.editorconfig)
root = true
[*.cs]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
# C# 代码样式规则
dotnet_sort_system_directives_first = true
dotnet_separate_import_directive_groups = false
# 命名约定
dotnet_naming_rule.interfaces_should_be_prefixed_with_i.severity = warning
dotnet_naming_rule.interfaces_should_be_prefixed_with_i.symbols = interface_symbols
dotnet_naming_rule.interfaces_should_be_prefixed_with_i.style = prefix_interface_with_i
dotnet_naming_symbols.interface_symbols.applicable_kinds = interface
dotnet_naming_style.prefix_interface_with_i.required_prefix = I
dotnet_naming_style.prefix_interface_with_i.capitalization = pascal_case
2.2 Visual Studio Code
安装和配置
# 安装 VS Code
# Windows: 下载安装包或使用 winget
winget install Microsoft.VisualStudioCode
# macOS: 使用 Homebrew
brew install --cask visual-studio-code
# Linux: 使用包管理器
sudo snap install code --classic
必需扩展
{
"recommendations": [
"ms-dotnettools.csharp",
"ms-dotnettools.vscode-dotnet-runtime",
"ms-vscode.vscode-json",
"ms-vscode.powershell",
"formulahendry.code-runner",
"ms-vscode.hexeditor",
"ms-dotnettools.blazorwasm-companion"
]
}
VS Code 配置文件
// .vscode/settings.json
{
"dotnet.defaultSolution": "disable",
"omnisharp.enableEditorConfigSupport": true,
"omnisharp.enableRoslynAnalyzers": true,
"csharp.semanticHighlighting.enabled": true,
"csharp.format.enable": true,
"editor.formatOnSave": true,
"files.exclude": {
"**/bin": true,
"**/obj": true
},
"search.exclude": {
"**/bin": true,
"**/obj": true
}
}
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/bin/Debug/net8.0/${workspaceFolderBasename}.dll",
"args": [],
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}
// .vscode/tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/${workspaceFolderBasename}.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/${workspaceFolderBasename}.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/${workspaceFolderBasename}.csproj"
],
"problemMatcher": "$msCompile"
}
]
}
2.3 JetBrains Rider
安装和配置
# 下载 Rider
# 访问 https://www.jetbrains.com/rider/
# 学生可以申请免费许可证
# 访问 https://www.jetbrains.com/student/
Rider 配置
// Rider 代码检查配置
// File -> Settings -> Editor -> Inspections
// 推荐启用的检查:
// - Code Quality Issues
// - Potential Code Quality Issues
// - Redundancies in Code
// - Constraints Violations
// - Declaration Redundancy
3. 命令行工具
3.1 .NET CLI 基础命令
# 创建新项目
dotnet new console -n MyConsoleApp
dotnet new classlib -n MyLibrary
dotnet new web -n MyWebApp
dotnet new mvc -n MyMvcApp
dotnet new webapi -n MyApiApp
dotnet new blazorserver -n MyBlazorApp
# 查看可用模板
dotnet new list
# 添加包引用
dotnet add package Newtonsoft.Json
dotnet add package Microsoft.EntityFrameworkCore
# 添加项目引用
dotnet add reference ../MyLibrary/MyLibrary.csproj
# 构建项目
dotnet build
dotnet build --configuration Release
# 运行项目
dotnet run
dotnet run --project MyWebApp
# 发布项目
dotnet publish -c Release -o ./publish
dotnet publish -c Release -r win-x64 --self-contained
# 测试项目
dotnet test
dotnet test --logger trx --results-directory ./TestResults
# 清理项目
dotnet clean
# 恢复包
dotnet restore
3.2 项目模板创建
# 创建自定义项目模板
mkdir MyTemplate
cd MyTemplate
# 创建 .template.config 目录
mkdir .template.config
# 创建模板配置文件
echo '{
"$schema": "http://json.schemastore.org/template",
"author": "Your Name",
"classifications": ["Common", "Console"],
"identity": "MyCompany.MyTemplate",
"name": "My Custom Template",
"shortName": "mytemplate",
"tags": {
"language": "C#",
"type": "project"
},
"sourceName": "MyTemplate",
"preferNameDirectory": true
}' > .template.config/template.json
# 安装模板
dotnet new install ./
# 使用模板
dotnet new mytemplate -n MyNewProject
3.3 有用的全局工具
# 安装有用的全局工具
dotnet tool install -g dotnet-ef # Entity Framework 工具
dotnet tool install -g dotnet-aspnet-codegenerator # ASP.NET Core 代码生成器
dotnet tool install -g dotnet-dump # 内存转储工具
dotnet tool install -g dotnet-trace # 性能跟踪工具
dotnet tool install -g dotnet-counters # 性能计数器
dotnet tool install -g dotnet-reportgenerator # 代码覆盖率报告
dotnet tool install -g dotnet-outdated # 检查过时的包
dotnet tool install -g dotnet-format # 代码格式化工具
# 查看已安装的工具
dotnet tool list -g
# 更新工具
dotnet tool update -g dotnet-ef
# 卸载工具
dotnet tool uninstall -g dotnet-ef
4. 项目结构和配置
4.1 解决方案结构
MySolution/
├── src/
│ ├── MyApp.Core/ # 核心业务逻辑
│ ├── MyApp.Infrastructure/ # 基础设施层
│ ├── MyApp.Web/ # Web 应用
│ └── MyApp.Api/ # API 服务
├── tests/
│ ├── MyApp.Core.Tests/ # 单元测试
│ ├── MyApp.Integration.Tests/ # 集成测试
│ └── MyApp.Performance.Tests/ # 性能测试
├── docs/ # 文档
├── scripts/ # 构建脚本
├── .gitignore
├── .editorconfig
├── Directory.Build.props # 全局项目属性
├── Directory.Build.targets # 全局构建目标
├── global.json # SDK 版本
├── nuget.config # NuGet 配置
└── MySolution.sln # 解决方案文件
4.2 项目文件配置
<!-- Directory.Build.props -->
<Project>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsAsErrors />
<WarningsNotAsErrors>CS1591</WarningsNotAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<PropertyGroup>
<Company>My Company</Company>
<Product>My Product</Product>
<Copyright>Copyright © My Company 2024</Copyright>
<Version>1.0.0</Version>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="8.0.0" PrivateAssets="all" />
</ItemGroup>
</Project>
<!-- 示例项目文件 MyApp.Core.csproj -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>MyApp.Core</RootNamespace>
<AssemblyName>MyApp.Core</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup>
</Project>
4.3 配置文件
// appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyAppDb;Trusted_Connection=true;MultipleActiveResultSets=true"
},
"AppSettings": {
"ApiKey": "your-api-key",
"MaxRetries": 3,
"TimeoutSeconds": 30
}
}
// appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyAppDb_Dev;Trusted_Connection=true;MultipleActiveResultSets=true"
}
}
5. 版本控制配置
5.1 Git 配置
# .gitignore 文件
echo '## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# NuGet Packages
*.nupkg
*.snupkg
.nuget/
# Others
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc' > .gitignore
# 初始化 Git 仓库
git init
git add .
git commit -m "Initial commit"
5.2 GitHub Actions 配置
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.0.x'
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore --configuration Release
- name: Test
run: dotnet test --no-build --configuration Release --verbosity normal --collect:"XPlat Code Coverage"
- name: Upload coverage reports
uses: codecov/codecov-action@v3
with:
file: ./coverage.xml
flags: unittests
name: codecov-umbrella
6. 调试和诊断工具
6.1 调试配置
// 调试辅助代码
using System;
using System.Diagnostics;
public class DebuggingExample
{
public static void Main()
{
// 条件编译
#if DEBUG
Console.WriteLine("Debug mode");
#endif
// 调试断言
Debug.Assert(DateTime.Now.Year >= 2024, "Year should be 2024 or later");
// 调试输出
Debug.WriteLine("Debug message");
Trace.WriteLine("Trace message");
// 条件方法
DebugMethod();
// 调试器检查
if (Debugger.IsAttached)
{
Console.WriteLine("Debugger is attached");
}
}
[Conditional("DEBUG")]
private static void DebugMethod()
{
Console.WriteLine("This method only runs in debug mode");
}
}
6.2 性能分析
using System;
using System.Diagnostics;
public class PerformanceExample
{
public static void Main()
{
// 使用 Stopwatch 测量性能
var stopwatch = Stopwatch.StartNew();
// 执行一些操作
DoSomeWork();
stopwatch.Stop();
Console.WriteLine($"Elapsed time: {stopwatch.ElapsedMilliseconds} ms");
// 内存使用情况
long memoryBefore = GC.GetTotalMemory(false);
// 执行一些操作
DoMemoryIntensiveWork();
long memoryAfter = GC.GetTotalMemory(false);
Console.WriteLine($"Memory used: {(memoryAfter - memoryBefore) / 1024} KB");
}
private static void DoSomeWork()
{
for (int i = 0; i < 1000000; i++)
{
// 模拟工作
}
}
private static void DoMemoryIntensiveWork()
{
var list = new System.Collections.Generic.List<string>();
for (int i = 0; i < 10000; i++)
{
list.Add($"Item {i}");
}
}
}
7. 包管理和依赖
7.1 NuGet 配置
<!-- nuget.config -->
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
<add key="MyCompany" value="https://pkgs.dev.azure.com/mycompany/_packaging/mycompany/nuget/v3/index.json" />
</packageSources>
<packageSourceCredentials>
<MyCompany>
<add key="Username" value="%NUGET_USERNAME%" />
<add key="ClearTextPassword" value="%NUGET_PASSWORD%" />
</MyCompany>
</packageSourceCredentials>
<config>
<add key="globalPackagesFolder" value="packages" />
</config>
</configuration>
7.2 常用包推荐
<!-- 常用 NuGet 包 -->
<ItemGroup>
<!-- 日志 -->
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<!-- JSON 处理 -->
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Text.Json" Version="8.0.0" />
<!-- HTTP 客户端 -->
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageReference Include="Polly" Version="8.2.0" />
<!-- 数据库 -->
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />
<!-- 测试 -->
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.6.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
<PackageReference Include="Moq" Version="4.20.69" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
</ItemGroup>
8. 实践练习
练习1:创建第一个 C# 项目
# 创建新的控制台应用
dotnet new console -n HelloWorld
cd HelloWorld
# 编辑 Program.cs
echo 'using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine($"Current time: {DateTime.Now}");
if (args.Length > 0)
{
Console.WriteLine($"Arguments: {string.Join(", ", args)}");
}
}
}
}' > Program.cs
# 运行项目
dotnet run
dotnet run -- arg1 arg2 arg3
练习2:配置开发环境
# 创建解决方案
dotnet new sln -n MyFirstSolution
# 创建类库项目
dotnet new classlib -n MyLibrary
dotnet sln add MyLibrary/MyLibrary.csproj
# 创建控制台项目
dotnet new console -n MyConsoleApp
dotnet sln add MyConsoleApp/MyConsoleApp.csproj
# 添加项目引用
cd MyConsoleApp
dotnet add reference ../MyLibrary/MyLibrary.csproj
# 构建解决方案
cd ..
dotnet build
9. 总结
本章介绍了 C# 开发环境的搭建和配置,包括:
- .NET SDK 安装:跨平台安装和版本管理
- IDE 选择:Visual Studio、VS Code、Rider 的配置
- 命令行工具:.NET CLI 的使用和全局工具
- 项目结构:标准的解决方案和项目组织
- 配置管理:项目文件、配置文件的设置
- 版本控制:Git 和 CI/CD 的配置
- 调试工具:调试和性能分析工具的使用
- 包管理:NuGet 的配置和常用包推荐
在下一章中,我们将学习 C# 的基本语法和数据类型。