Token导航 LogoToken导航TokenDH.com
AI 工具只读github未标认证来源可访问clear审计通过

csharp-advanced-patternscsharp 高级模式

Agent Skill

csharp-advanced-patterns 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

549

周安装

22

GitHub Stars

21

下载量

178
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:csharp-advanced-patterns(csharp 高级模式)
来源仓库:https://github.com/thapaliyabikendra/ai-artifacts
仓库路径:skills/csharp-advanced-patterns
安装命令:
npx skills add https://github.com/thapaliyabikendra/ai-artifacts --skill csharp-advanced-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/thapaliyabikendra/ai-artifacts --skill csharp-advanced-patterns

简介

用于复杂业务逻辑实现与异步编程优化,支持.NET 10新特性与现代C#模式应用。

  • 适用于性能敏感场景、遗留代码重构及不可变数据传输对象设计。
  • 提供records类型定义、Span/Memory内存操作与Result模式最佳实践指导。
  • 通过GitHub安装,需确认项目TargetFramework是否满足C# 12+要求。
  • 涉及批量数据处理时应优先使用异步流与值类型提升吞吐量。

SKILL.md

C# Advanced Patterns

Advanced C# language patterns and.NET 10 features for elegant, performant code.

When to Use

  • Implementing complex business logic with pattern matching
  • Optimizing async/await usage
  • Writing performant code with Span/Memory
  • Refactoring legacy code to modern C#
  • Creating immutable DTOs with records

Modern C# Features (.NET 10)

Records for DTOs

// Immutable DTO with required properties
public record CreatePatientDto
{
    public required string FirstName { get; init; }
    public required string LastName { get; init; }
    public required string Email { get; init; }
    public DateTime DateOfBirth { get; init; }
}

// Positional record with deconstruction
public record PatientDto(Guid Id, string FullName, string Email);

// Usage
var (id, name, email) = patient;

Pattern Matching

// Switch expression for status handling
public string GetStatusMessage(AppointmentStatus status) => status switch
{
    AppointmentStatus.Scheduled => "Your appointment is confirmed",
    AppointmentStatus.Completed => "Thank you for visiting",
    AppointmentStatus.Cancelled => "Your appointment was cancelled",
    AppointmentStatus.NoShow => "You missed your appointment",
    _ => throw new ArgumentOutOfRangeException(nameof(status))
};

// Property pattern matching
public decimal CalculateDiscount(Patient patient) => patient switch
{
    { Age: > 65 } => 0.20m,
    { IsVeteran: true } => 0.15m,
    { Visits: > 10 } => 0.10m,
    _ => 0m
};

// List patterns (.NET 7+)
public string DescribeList(int[] numbers) => numbers switch
{
    [] => "Empty",
    [var single] => $"Single: {single}",
    [var first, .., var last] => $"First: {first}, Last: {last}",
};

Primary Constructors

// Class with primary constructor
public class PatientService(
    IRepository<Patient, Guid> repository,
    ILogger<PatientService> logger)
{
    public async Task<Patient> GetAsync(Guid id)
    {
        logger.LogInformation("Getting patient {Id}", id);
        return await repository.GetAsync(id);
    }
}

Collection Expressions

// Modern collection initialization
int[] numbers = [1, 2, 3, 4, 5];
List<string> names = ["Alice", "Bob", "Charlie"];
Span<int> span = [1, 2, 3];

// Spread operator
int[] combined = [..numbers, 6, 7, 8];

Async/Await Patterns

Proper Async with Cancellation

public async Task<PatientDto> GetPatientAsync(
    Guid id,
    CancellationToken cancellationToken = default)
{
    var patient = await _repository
        .GetAsync(id, cancellationToken);

    return ObjectMapper.Map<Patient, PatientDto>(patient);
}

Parallel Processing with SemaphoreSlim

public async Task ProcessPatientsAsync(
    IEnumerable<Guid> patientIds,
    CancellationToken ct)
{
    var semaphore = new SemaphoreSlim(10); // Max 10 concurrent
    var tasks = patientIds.Select(async id =>
    {
        await semaphore.WaitAsync(ct);
        try
        {
            await ProcessPatientAsync(id, ct);
        }
        finally
        {
            semaphore.Release();
        }
    });

    await Task.WhenAll(tasks);
}

ValueTask for Hot Paths

// Use ValueTask when result is often synchronous
public ValueTask<Patient?> GetCachedPatientAsync(Guid id)
{
    if (_cache.TryGetValue(id, out var patient))
        return ValueTask.FromResult<Patient?>(patient);

    return new ValueTask<Patient?>(LoadPatientAsync(id));
}

Channel for Producer/Consumer

public class PatientProcessor
{
    private readonly Channel<Patient> _channel =
        Channel.CreateBounded<Patient>(100);

    public async Task ProduceAsync(Patient patient, CancellationToken ct)
    {
        await _channel.Writer.WriteAsync(patient, ct);
    }

    public async Task ConsumeAsync(CancellationToken ct)
    {
        await foreach (var patient in _channel.Reader.ReadAllAsync(ct))
        {
            await ProcessAsync(patient);
        }
    }
}

Result Pattern

public readonly record struct Result<T>
{
    public T? Value { get; }
    public string? Error { get; }
    public bool IsSuccess => Error is null;

    private Result(T value) => Value = value;
    private Result(string error) => Error = error;

    public static Result<T> Success(T value) => new(value);
    public static Result<T> Failure(string error) => new(error);

    public TResult Match<TResult>(
        Func<T, TResult> onSuccess,
        Func<string, TResult> onFailure)
        => IsSuccess ? onSuccess(Value!) : onFailure(Error!);
}

// Usage
public Result<Patient> CreatePatient(CreatePatientDto dto)
{
    if (string.IsNullOrEmpty(dto.Email))
        return Result<Patient>.Failure("Email is required");

    var patient = new Patient(dto.FirstName, dto.LastName, dto.Email);
    return Result<Patient>.Success(patient);
}

Extension Methods

public static class PatientExtensions
{
    public static string GetFullName(this Patient patient)
        => $"{patient.FirstName} {patient.LastName}";

    public static bool IsEligibleForDiscount(this Patient patient)
        => patient.Age > 65 || patient.Visits > 10;

    // IQueryable extension for reusable filters
    public static IQueryable<Patient> ActiveOnly(this IQueryable<Patient> query)
        => query.Where(p => p.IsActive);

    public static IQueryable<Patient> ByEmail(
        this IQueryable<Patient> query,
        string email)
        => query.Where(p => p.Email == email);
}

Performance Patterns

Span for Zero-Allocation

public static int CountOccurrences(ReadOnlySpan<char> text, char target)
{
    int count = 0;
    foreach (var c in text)
    {
        if (c == target) count++;
    }
    return count;
}

// String slicing without allocation
ReadOnlySpan<char> firstName = fullName.AsSpan(0, spaceIndex);

ArrayPool for Temporary Buffers

public async Task ProcessLargeDataAsync(Stream stream)
{
    var buffer = ArrayPool<byte>.Shared.Rent(4096);
    try
    {
        int bytesRead;
        while ((bytesRead = await stream.ReadAsync(buffer)) > 0)
        {
            ProcessChunk(buffer.AsSpan(0, bytesRead));
        }
    }
    finally
    {
        ArrayPool<byte>.Shared.Return(buffer);
    }
}

StringBuilder for String Building

// Bad: String concatenation in loops
string result = "";
foreach (var item in items)
    result += item; // Creates new string each iteration

// Good: Use StringBuilder
var sb = new StringBuilder();
foreach (var item in items)
    sb.Append(item);
return sb.ToString();

Anti-Patterns to Avoid

Anti-PatternProblemSolution
.Result / .Wait()Deadlock riskUse await
catch (Exception)Catches everythingCatch specific types
String concat in loopsO(n²) allocationsUse StringBuilder
async voidUnobserved exceptionsUse async Task
Premature optimizationComplexityProfile first
// Bad: Blocking on async
var result = GetPatientAsync(id).Result; // Deadlock risk!

// Good: Proper async
var result = await GetPatientAsync(id);

// Bad: async void (fire and forget)
async void ProcessPatient(Guid id) { ... }

// Good: async Task
async Task ProcessPatientAsync(Guid id) { ... }

// Bad: Catching base Exception
try { } catch (Exception ex) { }

// Good: Catch specific exceptions
try { }
catch (InvalidOperationException ex) { _logger.LogWarning(ex, "..."); }
catch (ArgumentException ex) { _logger.LogError(ex, "..."); }

LINQ Best Practices

// Avoid multiple enumeration
var patients = await _repository.GetListAsync(); // Materialize once
var count = patients.Count;
var first = patients.FirstOrDefault();

// Use AsNoTracking for read-only queries
var patients = await _context.Patients
    .AsNoTracking()
    .Where(p => p.IsActive)
    .ToListAsync();

// Prefer Any() over Count() > 0
if (await _repository.AnyAsync(p => p.Email == email)) { ... }

// Project early to reduce data transfer
var dtos = await _context.Patients
    .Where(p => p.IsActive)
    .Select(p => new PatientDto(p.Id, p.FullName, p.Email))
    .ToListAsync();

Quality Checklist

  • Use records for DTOs (immutability)
  • Use switch expressions over switch statements
  • Pass CancellationToken through async chain
  • Use ValueTask for hot paths with sync results
  • Avoid blocking calls (.Result,.Wait())
  • Use Span for performance-critical parsing
  • Catch specific exception types
  • Use nullable reference types

Integration Points

This skill is used by:

  • abp-developer: Modern C# patterns in implementation
  • abp-code-reviewer: Pattern validation during reviews
  • debugger: Performance analysis and fixes

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

github-copilot

27.79%
按下载量换算49

Cursor

26.43%
按下载量换算47

trae

19.33%
按下载量换算34

Claude Code

13.17%
按下载量换算23

OpenCode

7.42%
按下载量换算13

mcpjam

3.75%
按下载量换算7

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

只读

该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills