跳到正文
Skillpedia
通用编程48k · #5889

csharp

它能做什么

本指南教你遵循 C# 语言的最佳实践,更高效、更清晰地编写代码。文中展示了如何改进代码的部分内容,使其更易读、更易维护。

适用场景

  • ✓开始学习 C# 编程时。
  • ✓审查或改进已有的 C# 代码时。
  • ✓想编写更现代、更安全的 C# 代码时。

技能链接

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/csharp/SKILL.md

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/csharp/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“如何编写更简洁的 C# 代码来处理列表?”

每周 5 个新技能,1 分钟读完。

工作原理

本指南会并排展示 C# 中的旧写法和新写法,突出两者的差异,并解释为什么其中一种更好。

技术内容(原始 SKILL.md)

作者在 GitHub 上的英文原文。

C#: Idiomatic Efficiency Reference

When to Use

  • Use this skill when the task matches this description: Language-specific super-code guidelines for csharp.

Table of Contents

  1. LINQ & Collections
  2. Null Handling
  3. Async/Await
  4. Records & Pattern Matching
  5. Error Handling
  6. Resource Management
  7. Anti-patterns specific to C#

1. LINQ & Collections {#linq}

// ❌ Imperative accumulation
var result = new List<string>();
foreach (var item in items) {
    if (item.IsActive) result.Add(item.Name.ToUpper());
}

// ✅
var result = items
    .Where(i => i.IsActive)
    .Select(i => i.Name.ToUpper())
    .ToList();
// ❌ Manual grouping
var grouped = new Dictionary<string, List<Item>>();
foreach (var item in items) {
    if (!grouped.ContainsKey(item.Category))
        grouped[item.Category] = new List<Item>();
    grouped[item.Category].Add(item);
}

// ✅
var grouped = items.GroupBy(i => i.Category)
    .ToDictionary(g => g.Key, g => g.ToList());
// ❌ Checking Any() then First()
if (items.Any(i => i.IsValid)) {
    var first = items.First(i => i.IsValid);
}

// ✅
var first = items.FirstOrDefault(i => i.IsValid);
if (first is not null) { ... }

Prefer method syntax for chains of 2+ operations. Query syntax is fine for complex joins.


2. Null Handling {#nulls}

// ❌ Nested null checks
string city = null;
if (user != null && user.Address != null) {
    city = user.Address.City;
}

// ✅
var city = user?.Address?.City;
// ❌ Ternary for null fallback
var name = user != null ? user.Name : "Unknown";

// ✅
var name = user?.Name ?? "Unknown";
// ❌ Null check before event invocation
if (OnChanged != null) OnChanged(this, args);

// ✅
OnChanged?.Invoke(this, args);
// ❌ Throwing ArgumentNullException manually
if (name == null) throw new ArgumentNullException(nameof(name));

// ✅ (C# 10+)
ArgumentNullException.ThrowIfNull(name);

Enable nullable reference types (<Nullable>enable</Nullable>) project-wide.


3. Async/Await {#async}

// ❌ Blocking on async code
var result = GetDataAsync().Result; // deadlock risk

// ✅
var result = await GetDataAsync();
// ❌ async void (exceptions are unobservable)
async void OnButtonClick() { await DoWork(); }

// ✅ — async Task; only async void for event handlers that truly require it
async Task OnButtonClick() { await DoWork(); }
// ❌ Sequential awaits for independent work
var a = await FetchA();
var b = await FetchB();

// ✅
var (a, b) = (await Task.WhenAll(FetchA(), FetchB())) switch
{
    var r => (r[0], r[1])
};
// or cleaner with ValueTuple:
var taskA = FetchA();
var taskB = FetchB();
var a = await taskA;
var b = await taskB;
// ❌ Wrapping synchronous code in Task.Run inside a library
public Task<int> GetValue() => Task.Run(() => ComputeSync());

// ✅ — let the caller decide; expose sync method
public int GetValue() => ComputeSync();

Add ConfigureAwait(false) in library code. Omit in app/UI code.


4. Records & Pattern Matching {#records}

// ❌ Manual equality, ToString, Deconstruct for data types
class Point {
    public int X { get; init; }
    public int Y { get; init; }
    // + Equals, GetHashCode, ToString...
}

// ✅ (C# 9+)
record Point(int X, int Y);
// ❌ if-else chain for type checking
if (shape is Circle) {
    var c = (Circle)shape;
    return c.Radius * c.Radius * Math.PI;
} else if (shape is Rectangle) { ... }

// ✅
return shape switch {
    Circle { Radius: var r } => r * r * Math.PI,
    Rectangle { Width: var w, Height: var h } => w * h,
    _ => throw new ArgumentException($"Unknown shape: {shape}")
};
// ❌ Range checking with && 
if (score >= 0 && score <= 100) { ... }

// ✅ (C# 9+)
if (score is >= 0 and <= 100) { ... }

5. Error Handling {#errors}

// ❌ Catching Exception to log and swallow
try { Process(); }
catch (Exception ex) { logger.LogError(ex, "error"); }

// ✅ — catch specific, rethrow if you can't handle
try { Process(); }
catch (HttpRequestException ex) {
    throw new ServiceException("upstream failure", ex);
}
// ❌ throw ex (resets stack trace)
catch (Exception ex) { throw ex; }

// ✅
catch (Exception ex) { throw; } // preserves stack trace
// or wrap: throw new AppException("context", ex);

…
常见问题

什么是 LINQ?

LINQ(语言集成查询)是一种直接在 C# 语言中查询和处理数据集合的方式,能让代码更简洁。

“Async/Await”是什么意思?

Async 和 Await 是两个关键字,用于编写在后台执行任务而不会让主程序卡住的代码,从而提升程序的响应速度。

C# 中的“Records”是什么?

Records 是 C# 中一种特殊的类,用于简化创建以数据为核心、不可变的类型。它会自动提供相等性比较和字符串表示等功能。

详情

作者的原始描述

Language-specific super-code guidelines for csharp.

repo: sickn33/agentic-awesome-skills

热度

GitHub 星标
48k
排名
#5889
许可证
MIT
更新时间
2026/10/15

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能