Token导航 LogoToken导航

Agent Skill · 开发

dotnet-csharp-source-generators(dotnet csharp 源生成器)

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

dotnet-csharp-source-generators 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为只读;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 16,704。

总安装 475周安装 20GitHub Stars 16下载 166核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

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

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

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-csharp-source-generators

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

该技能指导 Roslyn 源生成器的创建与使用,涵盖诊断报告和测试方法。适用于需要自动生成代码的 .NET 项目,如正则表达式和 JSON 序列化。核心能力包括增量生成器实现、语义分析和常用属性消费模式。使用时应结合现代 C# 特性和命名规范确保生成代码质量。

安装前需确认项目支持 .NET Standard 2.0+ 和 Roslyn API。

来源仓库内路径:skills/dotnet-csharp-source-generators

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-csharp-s…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它标注为只读,先用只读任务试一次,确认行为符合预期再扩大使用范围。

常见问题

6 条

dotnet-csharp-source-generators 怎么安装?

在终端执行 npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-csharp-source-gene…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

dotnet-csharp-source-generators 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

dotnet-csharp-source-generators 需要什么权限?

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

dotnet-csharp-source-generators 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

dotnet-csharp-source-generators 用的人多吗?

公开数据是累计安装 475 次,近一周安装 20 次,下载 166 次,GitHub 16 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

dotnet-csharp-source-generators 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。
  • 标注为只读权限,试用阶段不容易误改本地文件。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。
  • 只想先试试效果、不希望它改动本地文件的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
dotnet-csharp-source-generators

dotnet csharp 源生成器 · 本页

47516只读未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

dotnet-csharp-source-generators

Guidance for both creating and consuming Roslyn source generators in.NET. Creating: IIncrementalGenerator, syntax providers, semantic analysis, emit patterns, diagnostic reporting, testing with CSharpGeneratorDriver. Consuming: [GeneratedRegex], [LoggerMessage], System.Text.Json source generation, [JsonSerializable].

Cross-references: [skill:dotnet-csharp-modern-patterns] for partial properties and related C# features, [skill:dotnet-csharp-coding-standards] for naming conventions.


Creating Source Generators

Project Setup

Source generators are shipped as analyzers targeting netstandard2.0.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
    <IsRoslynComponent>true</IsRoslynComponent>
    <LangVersion>latest</LangVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" />
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.12.0" PrivateAssets="all" />
  </ItemGroup>
</Project>
Always target netstandard2.0. Generators load into the compiler process, which requires this TFM for compatibility. Use LangVersion>latest to write modern C# in the generator itself.

IIncrementalGenerator (Preferred)

Always use IIncrementalGenerator over the legacy ISourceGenerator. Incremental generators are cache-aware and only re-run when inputs change, making them significantly faster in IDE scenarios.

[Generator]
public sealed class AutoNotifyGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        // Step 1: Filter syntax nodes to candidate fields
        var fieldDeclarations = context.SyntaxProvider
            .ForAttributeWithMetadataName(
                "MyLib.AutoNotifyAttribute",
                predicate: static (node, _) => node is FieldDeclarationSyntax,
                transform: static (ctx, _) => GetFieldInfo(ctx))
            .Where(static info => info is not null)
            .Select(static (info, _) => info!.Value);

        // Step 2: Group fields by containing type, then emit one file per type
        context.RegisterSourceOutput(fieldDeclarations.Collect(),
            static (spc, fields) => Execute(fields, spc));
    }

    private static FieldInfo? GetFieldInfo(
        GeneratorAttributeSyntaxContext context)
    {
        var fieldSymbol = context.TargetSymbol as IFieldSymbol;
        if (fieldSymbol is null)
            return null;

        var containingType = fieldSymbol.ContainingType;

        // Use fully qualified type name to handle generic and nested types
        var fullTypeName = containingType.ToDisplayString(
            SymbolDisplayFormat.FullyQualifiedFormat
                .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted));

        return new FieldInfo(
            fieldSymbol.ContainingNamespace.IsGlobalNamespace
                ? ""
                : fieldSymbol.ContainingNamespace.ToDisplayString(),
            containingType.Name,
            fullTypeName,
            fieldSymbol.Name,
            fieldSymbol.Type.ToDisplayString());
    }

    private static void Execute(
        ImmutableArray<FieldInfo> fields,
        SourceProductionContext context)
    {
        // Group by fully qualified type name to emit one file per class
        foreach (var group in fields.GroupBy(f => f.FullTypeName))
        {
            var first = group.First();
            var ns = first.Namespace;
            var className = first.ClassName;
            var properties = new StringBuilder();

            foreach (var field in group)
            {
                var propertyName = GetPropertyName(field.FieldName);
                properties.AppendLine($$"""
                        public {{field.FieldType}} {{propertyName}}
                        {
                            get => {{field.FieldName}};
                            set
                            {
                                if (!global::System.Collections.Generic.EqualityComparer<{{field.FieldType}}>.Default.Equals({{field.FieldName}}, value))
                                {
                                    {{field.FieldName}} = value;
                                    PropertyChanged?.Invoke(this,
                                        new global::System.ComponentModel.PropertyChangedEventArgs(nameof({{propertyName}})));
                                }
                            }
                        }
                    """);
            }

            // Handle global namespace (no namespace declaration)
            var nsBlock = string.IsNullOrEmpty(ns) ? "" : $"namespace {ns};\n\n";

            var source = $$"""
                // <auto-generated/>
                #nullable enable

                {{nsBlock}}partial class {{className}}
                    : global::System.ComponentModel.INotifyPropertyChanged
                {
                    public event global::System.ComponentModel.PropertyChangedEventHandler? PropertyChanged;

                {{properties}}
                }
                """;

            // Include namespace in hint name to avoid collisions across namespaces
            var hintPrefix = string.IsNullOrEmpty(ns) ? className : $"{ns}.{className}";
            context.AddSource($"{hintPrefix}.AutoNotify.g.cs", source);
        }
    }

    private static string GetPropertyName(string fieldName)
        => fieldName.TrimStart('_') is [var first, .. var rest]
            ? $"{char.ToUpperInvariant(first)}{rest}"
            : fieldName;
}

internal readonly record struct FieldInfo(
    string Namespace,
    string ClassName,
    string FullTypeName,
    string FieldName,
    string FieldType);
Scope note: This example targets top-level, non-generic classes for clarity. A production generator should also handle generic type parameters (emitting matching partial class Foo<T> declarations) and nested types (emitting nested partial class hierarchies). Report a diagnostic for unsupported shapes rather than emitting invalid code.

Key Pipeline Design Rules

  1. Filter early -- Use ForAttributeWithMetadataName or CreateSyntaxProvider with a tight predicate to minimize work.
  2. Transform to simple data -- Extract only the data you need (strings, records) in the transform step. Never pass ISymbol or SyntaxNode through the pipeline (they hold the compilation alive and break caching).
  3. Use value equality -- Pipeline outputs are compared by value. Use record struct or implement IEquatable<T> for custom types.
  4. Emit deterministic output -- Same inputs must produce identical source. Use // <auto-generated/> and #nullable enable headers.

Syntax Providers

// ForAttributeWithMetadataName -- most common, filters by attribute
var candidates = context.SyntaxProvider.ForAttributeWithMetadataName(
    "MyLib.GenerateMapperAttribute",
    predicate: static (node, _) => node is ClassDeclarationSyntax,
    transform: static (ctx, _) => /* extract info */);

// CreateSyntaxProvider -- general-purpose, any syntax predicate
var candidates = context.SyntaxProvider.CreateSyntaxProvider(
    predicate: static (node, _) => node is MethodDeclarationSyntax m
        && m.Modifiers.Any(SyntaxKind.PartialKeyword),
    transform: static (ctx, _) => /* extract info */);

Diagnostic Reporting

Report errors and warnings through SourceProductionContext rather than throwing exceptions. To report location-specific diagnostics, include a Location in your pipeline data (captured from the syntax node in the transform step).

private static readonly DiagnosticDescriptor InvalidFieldType = new(
    id: "AN001",
    title: "Invalid field type for AutoNotify",
    messageFormat: "Field '{0}' must be a non-pointer type",
    category: "AutoNotify",
    defaultSeverity: DiagnosticSeverity.Error,
    isEnabledByDefault: true);

// In the transform step, capture location:
var location = context.TargetNode.GetLocation();

// In the Execute method, report with location:
context.ReportDiagnostic(Diagnostic.Create(
    InvalidFieldType,
    location,       // captured from syntax node, not from projected data
    fieldName));
Note: Location is not value-equatable, so including it in your pipeline record breaks incremental caching. A common pattern is to carry it as a separate field that you exclude from equality, or report diagnostics in a CreateSyntaxProvider step before projecting to value types.

Emit Patterns

// Prefer raw string literals for templates (C# 11+, in the generator project)
var source = $$"""
    // <auto-generated/>
    #nullable enable

    namespace {{ns}};

    partial class {{className}}
    {
        {{generatedMembers}}
    }
    """;

context.AddSource($"{className}.g.cs", source);

File naming convention: {TypeName}.{Feature}.g.cs -- the .g.cs suffix signals generated code and is excluded by many linters.

Post-Init Output (Static Source)

Use RegisterPostInitializationOutput for marker attributes and helper types that do not depend on user code:

context.RegisterPostInitializationOutput(static ctx =>
{
    ctx.AddSource("AutoNotifyAttribute.g.cs", """
        // <auto-generated/>
        namespace MyLib;

        [System.AttributeUsage(System.AttributeTargets.Field)]
        internal sealed class AutoNotifyAttribute : System.Attribute { }
        """);
});

Testing Source Generators

Use CSharpGeneratorDriver to run generators in-memory and verify output.

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

[Fact]
public void Generator_ProducesExpectedOutput()
{
    // Arrange
    var source = """
        using MyLib;

        namespace TestApp;

        public partial class ViewModel
        {
            [AutoNotify]
            private string _name = "";
        }
        """;

    var syntaxTree = CSharpSyntaxTree.ParseText(source);
    var references = AppDomain.CurrentDomain.GetAssemblies()
        .Where(a => !a.IsDynamic && !string.IsNullOrEmpty(a.Location))
        .Select(a => MetadataReference.CreateFromFile(a.Location))
        .Cast<MetadataReference>()
        .ToList();

    var compilation = CSharpCompilation.Create("TestAssembly",
        [syntaxTree],
        references,
        new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

    var generator = new AutoNotifyGenerator();

    // Act
    GeneratorDriver driver = CSharpGeneratorDriver.Create(generator);
    driver = driver.RunGeneratorsAndUpdateCompilation(
        compilation, out var outputCompilation, out var diagnostics);

    // Assert
    Assert.Empty(diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error));

    var runResult = driver.GetRunResult();
    Assert.Single(runResult.GeneratedTrees);

    var generatedSource = runResult.GeneratedTrees[0].GetText().ToString();
    Assert.Contains("public string Name", generatedSource);
}

Snapshot Testing (Verify)

For more robust testing, use the Verify.SourceGenerators package to snapshot-test generated output:

[Fact]
public Task Generator_SnapshotTest()
{
    var source = """
        using MyLib;
        namespace TestApp;
        public partial class ViewModel
        {
            [AutoNotify]
            private string _name = "";
        }
        """;

    return TestHelper.Verify(source);
}

Consuming Built-In Source Generators

[GeneratedRegex] (net7.0+)

Compile-time regex generation. Zero runtime compilation cost, AOT-compatible.

public partial class Validators
{
    [GeneratedRegex(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
        RegexOptions.Compiled | RegexOptions.IgnoreCase)]
    private static partial Regex EmailRegex();

    public static bool IsValidEmail(string email)
        => EmailRegex().IsMatch(email);
}

Key rules:

  • Method must be static partial returning Regex
  • Place on partial class (or partial struct)
  • Replaces new Regex(...) with zero allocation at runtime
  • Supports all RegexOptions except RegexOptions.Compiled (which is ignored -- the source generator replaces it)

[LoggerMessage] (net6.0+)

High-performance structured logging with zero-allocation at log-disabled levels.

public static partial class LogMessages
{
    [LoggerMessage(Level = LogLevel.Information,
        Message = "Processing order {OrderId} for customer {CustomerId}")]
    public static partial void OrderProcessing(
        this ILogger logger, int orderId, string customerId);

    [LoggerMessage(Level = LogLevel.Error,
        Message = "Failed to process order {OrderId}")]
    public static partial void OrderProcessingFailed(
        this ILogger logger, int orderId, Exception exception);
}

// Usage
logger.OrderProcessing(order.Id, order.CustomerId);

Key rules:

  • Methods must be static partial in a partial class
  • Parameters matching {Placeholder} in the message are logged as structured data
  • Exception parameter is logged automatically (do not include in message template)
  • Event IDs are auto-assigned if not specified; specify explicit IDs for stable telemetry

System.Text.Json Source Generation (net6.0+)

AOT-compatible JSON serialization. Eliminates runtime reflection.

[JsonSerializable(typeof(Order))]
[JsonSerializable(typeof(List<Order>))]
[JsonSerializable(typeof(Customer))]
[JsonSourceGenerationOptions(
    PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
public partial class AppJsonContext : JsonSerializerContext;
Registration in ASP.NET Core
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default);
});

// Or for Minimal APIs
app.MapGet("/orders/{id}", async (int id, IOrderService service) =>
{
    var order = await service.GetByIdAsync(id);
    return order is not null
        ? Results.Ok(order)
        : Results.NotFound();
});
Manual Serialization
// Serialize
var json = JsonSerializer.Serialize(order, AppJsonContext.Default.Order);

// Deserialize
var order = JsonSerializer.Deserialize(json, AppJsonContext.Default.Order);

// With stream
await JsonSerializer.SerializeAsync(stream, orders,
    AppJsonContext.Default.ListOrder);

Key rules:

  • Register all types that need serialization in [JsonSerializable] attributes
  • Use TypeInfoResolverChain (net8.0+) to combine multiple contexts
  • Required for Native AOT -- reflection-based serialization is trimmed
  • See [skill:dotnet-csharp-modern-patterns] for related C# features used in generated code

[JsonSerializable] with Polymorphism (net7.0+)

[JsonDerivedType(typeof(CreditCardPayment), "credit")]
[JsonDerivedType(typeof(BankTransferPayment), "bank")]
public abstract class Payment
{
    public decimal Amount { get; init; }
}

public class CreditCardPayment : Payment
{
    public required string CardLast4 { get; init; }
}

public class BankTransferPayment : Payment
{
    public required string AccountNumber { get; init; }
}

[JsonSerializable(typeof(Payment))]
public partial class PaymentJsonContext : JsonSerializerContext;

Generator Reference: Packaging and Consumption

Referencing a Generator in a Consuming Project

<ItemGroup>
  <ProjectReference Include="..\MyGenerator\MyGenerator.csproj"
                    OutputItemType="Analyzer"
                    ReferenceOutputAssembly="false" />
</ItemGroup>

NuGet Package Layout

When shipping a generator as a NuGet package, place the assembly under analyzers/dotnet/cs/:

MyGenerator.nupkg
  analyzers/
    dotnet/
      cs/
        MyGenerator.dll
  lib/
    netstandard2.0/
      _._   (empty placeholder if no runtime dependency)
<!-- In the generator .csproj -->
<PropertyGroup>
  <IncludeBuildOutput>false</IncludeBuildOutput>
  <DevelopmentDependency>true</DevelopmentDependency>
</PropertyGroup>

<ItemGroup>
  <None Include="$(OutputPath)\$(AssemblyName).dll"
        Pack="true"
        PackagePath="analyzers/dotnet/cs" />
</ItemGroup>

Debugging Source Generators

// Add to Initialize() for attach-debugger workflow
#if DEBUG
if (!System.Diagnostics.Debugger.IsAttached)
{
    System.Diagnostics.Debugger.Launch();
}
#endif

Alternatively, emit generated files to disk for inspection:

<!-- In the consuming project -->
<PropertyGroup>
  <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
  <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
</PropertyGroup>

Add Generated/ to .gitignore.


References

平台分布

Codex

37.41%
按下载量换算62

Claude

32.89%
按下载量换算55

Cursor

18.77%
按下载量换算31

Gemini CLI

8.74%
按下载量换算15

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

只读

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

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills