Csharp 标志

Csharp

社区
alpham8
csharp

编写 C# 代码时使用,涵盖现代 C# 12/13 功能、记录、模式匹配、可空引用类型、LINQ、async/await、集合、泛型、密封类、必需属性和文件范围命名空间。出现 .cs 文件、.csproj、C# 类、接口或记录时触发。

Add to TypingMind

概览

发布者alpham8
代码仓库agentic-webdev
技能名称csharp
星标数
4
复刻数
0
附带文件
仅含指令
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 alpham8 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Csharp AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/alpham8/agentic-webdev/tree/master/skills/csharp
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/alpham8/agentic-webdev.git /tmp/agentic-webdev
mkdir -p .claude/skills
cp -r /tmp/agentic-webdev/skills/csharp .claude/skills/csharp
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Csharp,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Csharp。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Csharp 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

C#

Related Skills

NeedSkill
ASP.NET Core framework (DI, middleware, APIs, EF Core)aspnet-core
TypeScript (frontend, similar type system concepts)typescript

Overview

C# is a strongly-typed, object-oriented language running on .NET. Current version: C# 13 (.NET 9).

Key principles: Nullable reference types enabled, sealed by default for services, records for DTOs, async all the way, explicit types over var.


Modern C# Features

File-Scoped Namespaces (C# 10)

csharp
// One line instead of wrapping the entire file
namespace App.Services;

public sealed class OrderService : IOrderService
{
    // ...
}

Records (C# 9+)

csharp
// Immutable data transfer objects
public sealed record UserDto(string Id, string DisplayName, string? AvatarUrl);

// Record with additional logic
public sealed record Money(decimal Amount, string Currency)
{
    public Money Add(Money other)
    {
        if (Currency != other.Currency)
        {
            throw new InvalidOperationException("Currency mismatch");
        }
        return this with { Amount = Amount + other.Amount };
    }
}

// Record struct (value type, no heap allocation)
public readonly record struct Coordinate(double Lat, double Lng);

// Positional record with extra properties
public sealed record DetectedFace(float X, float Y, float Width, float Height)
{
    public float Area => Width * Height;
}

Required Properties (C# 11)

csharp
public sealed class CreatePostRequest
{
    public required string Content { get; init; }
    public required string NetworkSlug { get; init; }
    public List<string>? MediaIds { get; init; }
}

Nullable Reference Types

csharp
// Enable in .csproj: <Nullable>enable</Nullable>

public sealed class UserService
{
    // Non-nullable: compiler guarantees non-null
    private readonly ILogger<UserService> _logger;

    // Nullable: explicitly optional
    public async Task<UserDto?> FindByEmailAsync(string email)
    {
        ApplicationUser? user = await _context.Users
            .FirstOrDefaultAsync(u => u.Email == email);

        if (user is null)
        {
            return null;
        }

        return MapToDto(user);
    }
}

Pattern Matching

csharp
// Type patterns
public string Describe(object value) => value switch
{
    int i when i > 0 => $"Positive: {i}",
    int i => $"Non-positive: {i}",
    string s => $"String: {s}",
    null => "null",
    _ => $"Unknown: {value.GetType().Name}",
};

// Property patterns
public decimal CalculateDiscount(Order order) => order switch
{
    { Total: > 1000, IsPremium: true } => order.Total * 0.2m,
    { Total: > 500 } => order.Total * 0.1m,
    { IsPremium: true } => order.Total * 0.05m,
    _ => 0m,
};

// List patterns (C# 11)
int[] numbers = [1, 2, 3, 4, 5];
bool isValid = numbers is [1, 2, ..]; // starts with 1, 2

// Relational patterns
string GetCategory(int score) => score switch
{
    >= 90 => "Excellent",
    >= 70 => "Good",
    >= 50 => "Average",
    _ => "Below average",
};

Primary Constructors (C# 12)

csharp
// Classes with primary constructor (DI-friendly)
public sealed class ChatService(
    ActionBuddiesDbContext context,
    ILogger<ChatService> logger,
    ICacheService cache) : IChatService
{
    public async Task<ChatResponse> CreateDirectChatAsync(string userId, string participantId)
    {
        logger.LogInformation("Creating chat between {UserId} and {ParticipantId}", userId, participantId);
        // context, logger, cache available as fields
    }
}

Collection Expressions (C# 12)

csharp
// Spread and initialize
List<string> combined = [..existing, "new item", ..more];
int[] numbers = [1, 2, 3, 4, 5];
ReadOnlySpan<byte> buffer = [0x00, 0xFF];

Raw String Literals (C# 11)

csharp
string json = """
    {
        "name": "ActionBuddies",
        "version": "1.0"
    }
    """;

// Interpolated raw strings
string query = $"""
    SELECT * FROM users
    WHERE email = '{email}'
    AND active = true
    """;

Sealed Classes

csharp
// Sealed prevents inheritance -- use for services, handlers, DTOs
public sealed class NotificationService : INotificationService
{
    // Cannot be subclassed -- explicit design intent
}

Target-Typed New

csharp
List<UserDto> users = new();
Dictionary<string, int> counts = new();
CancellationTokenSource cts = new(TimeSpan.FromSeconds(30));

Type System

Value Types vs Reference Types

csharp
// Value types (stack-allocated)
int count = 0;
decimal price = 9.99m;
bool active = true;
DateTime now = DateTime.UtcNow;
Guid id = Guid.NewGuid();
Status status = Status.Active;    // enum
Coordinate point = new(48.1, 11.5); // record struct

// Reference types (heap-allocated)
string name = "Alice";
List<int> numbers = [1, 2, 3];
UserDto? user = null;

Enums

csharp
public enum ModerationAction
{
    Warn,
    Suspend7Days,
    Suspend30Days,
    Ban,
    Escalate,
}

// String backing (for JSON serialization)
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum NotificationType
{
    Like,
    Comment,
    Follow,
    Mention,
    EventInvite,
}

Interfaces

csharp
public interface IChatService
{
    Task<ChatResponse> CreateDirectChatAsync(string currentUserId, string participantUserId);
    Task<List<ChatMessageDto>> GetMessagesAsync(string chatId, string userId, int page, int pageSize);
    Task<ChatMessageDto> SendMessageAsync(string chatId, string senderId, string content);
    Task DeleteMessageAsync(string chatId, string messageId, string userId);
}

Generics

csharp
public interface IRepository<T> where T : class
{
    Task<T?> FindByIdAsync(int id);
    Task<List<T>> FindAllAsync(CancellationToken ct = default);
    Task AddAsync(T entity, CancellationToken ct = default);
}

// Generic constraints
public sealed class CachedService<TKey, TValue>(ICacheService cache)
    where TKey : notnull
    where TValue : class
{
    public async Task<TValue?> GetOrSetAsync(TKey key, Func<Task<TValue>> factory, TimeSpan ttl)
    {
        string cacheKey = $"{typeof(TValue).Name}:{key}";
        TValue? cached = await cache.GetAsync<TValue>(cacheKey);

        if (cached is not null)
        {
            return cached;
        }

        TValue value = await factory();
        await cache.SetAsync(cacheKey, value, ttl);
        return value;
    }
}

LINQ

csharp
// Query syntax (less common in modern C#)
var result = from u in users
             where u.IsActive
             orderby u.Name
             select new UserDto(u.Id, u.Name, u.AvatarUrl);

// Method syntax (preferred)
List<UserDto> activeUsers = await context.Users
    .Where(u => u.IsActive)
    .OrderBy(u => u.DisplayName)
    .Select(u => new UserDto(u.Id, u.DisplayName, u.AvatarUrl))
    .ToListAsync();

// Common operators
int count = items.Count(i => i.IsValid);
UserDto? first = items.FirstOrDefault(i => i.Id == targetId);
bool any = items.Any(i => i.Score > 90);
bool all = items.All(i => i.Score >= 0);
decimal avg = items.Average(i => i.Price);
decimal sum = items.Sum(i => i.Amount);
List<string> distinct = items.Select(i => i.Category).Distinct().ToList();

// Grouping
Dictionary<string, List<Post>> byNetwork = posts
    .GroupBy(p => p.NetworkSlug)
    .ToDictionary(g => g.Key, g => g.ToList());

// Projection with index
List<(int Index, string Name)> indexed = items
    .Select((item, index) => (index, item.Name))
    .ToList();

Async / Await

csharp
// Async all the way -- never .Result or .Wait()
public async Task<PostDto> CreatePostAsync(CreatePostRequest request, string userId)
{
    Post post = new()
    {
        Content = request.Content,
        AuthorId = userId,
        CreatedAt = DateTime.UtcNow,
    };

    context.Posts.Add(post);
    await context.SaveChangesAsync();

    return MapToDto(post);
}

// Parallel async
public async Task<SearchResult> SearchAsync(string query)
{
    Task<List<UserDto>> usersTask = SearchUsersAsync(query);
    Task<List<PostDto>> postsTask = SearchPostsAsync(query);
    Task<List<SpotDto>> spotsTask = SearchSpotsAsync(query);
    Task<List<EventDto>> eventsTask = SearchEventsAsync(query);

    await Task.WhenAll(usersTask, postsTask, spotsTask, eventsTask);

    return new SearchResult
    {
        Users = usersTask.Result,
        Posts = postsTask.Result,
        Spots = spotsTask.Result,
        Events = eventsTask.Result,
    };
}

// CancellationToken propagation
public async Task<List<PostDto>> GetFeedAsync(string userId, int page, CancellationToken ct)
{
    return await context.Posts
        .Where(p => p.NetworkSlug == networkSlug)
        .OrderByDescending(p => p.CreatedAt)
        .Skip((page - 1) * 20)
        .Take(20)
        .Select(p => MapToDto(p))
        .ToListAsync(ct);
}

Collections

csharp
// Immutable collections
IReadOnlyList<string> names = ["Alice", "Bob"];
IReadOnlyDictionary<string, int> scores = new Dictionary<string, int>
{
    ["Alice"] = 95,
    ["Bob"] = 87,
};

// Frozen collections (.NET 8+ -- optimized for read-heavy)
FrozenDictionary<string, Sport> sportsLookup = sports.ToFrozenDictionary(s => s.Slug);

// Array slicing
int[] arr = [1, 2, 3, 4, 5];
int[] slice = arr[1..3];      // [2, 3]
int last = arr[^1];           // 5
int[] lastTwo = arr[^2..];    // [4, 5]

String Handling

csharp
// Interpolation
string msg = $"User {user.DisplayName} (ID: {user.Id}) logged in";

// Verbatim + interpolation
string path = $@"C:\Users\{username}\Documents";

// String.Join, Split
string csv = string.Join(", ", items.Select(i => i.Name));
string[] parts = input.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);

// StringBuilder for loops
StringBuilder sb = new();
foreach (string item in items)
{
    sb.AppendLine(item);
}

// Span-based (zero allocation)
ReadOnlySpan<char> span = input.AsSpan();
bool startsWith = span.StartsWith("prefix");

Error Handling

csharp
// Specific exceptions
public sealed class PostNotFoundException : Exception
{
    public PostNotFoundException(string postId)
        : base($"Post with ID '{postId}' was not found") { }
}

// Guard clauses with ArgumentException helpers (.NET 8+)
public void SetName(string name)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(name);
    ArgumentOutOfRangeException.ThrowIfGreaterThan(name.Length, 100);
    _name = name;
}

// Try pattern (no exceptions for expected failures)
public bool TryGetUser(string id, out UserDto? user)
{
    user = _cache.Get<UserDto>(id);
    return user is not null;
}

Common Gotchas

  1. var hides types -- Use explicit types for clarity, especially in service code. var is acceptable for new() and LINQ where the type is obvious.
  2. Async void -- Never use async void except in event handlers. Always return Task or Task<T>.
  3. .Result / .Wait() deadlocks -- Never block on async code. Use await all the way up.
  4. string.IsNullOrEmpty vs IsNullOrWhiteSpace -- Prefer IsNullOrWhiteSpace to also catch " ".
  5. DateTime.Now vs DateTime.UtcNow -- Always use UtcNow for storage and comparison. Convert to local only for display.
  6. EF Core tracking -- Use .AsNoTracking() for read-only queries to avoid memory and performance overhead.
  7. IEnumerable multiple enumeration -- Materialize with .ToList() if you iterate more than once.
  8. Sealed classes -- Seal service implementations. Unsealed classes have virtual dispatch overhead and invite uncontrolled inheritance.
  9. Dispose pattern -- IDisposable / IAsyncDisposable resources need using statements or DI lifetime management.
  10. ConfigureAwait(false) -- Not needed in ASP.NET Core (no SynchronizationContext). Required in library code targeting multiple platforms.
  11. Nullable warnings -- Never suppress with ! without justification. Use is not null checks or ?? instead.
  12. Mutable records -- Records with { get; set; } lose immutability benefits. Use { get; init; } or positional records.

Documentation References

常见问题

Csharp AI 技能有什么作用?

编写 C# 代码时使用,涵盖现代 C# 12/13 功能、记录、模式匹配、可空引用类型、LINQ、async/await、集合、泛型、密封类、必需属性和文件范围命名空间。出现 .cs 文件、.csproj、C# 类、接口或记录时触发。

为什么在 TypingMind 中使用 Csharp?

因为您只需安装一次,就能搭配任何模型使用。Csharp 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Csharp?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/alpham8/agentic-webdev/tree/master/skills/csharp。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Csharp?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Csharp 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Csharp 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Csharp AI 技能免费吗?

alpham8 已在 GitHub 上发布了该技能。请查看代码仓库了解许可条款。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇