用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/Tyler-R-Kendrick/agent-skills --skill dotnet-cheatsheet命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
基于 SOC 职业分类
正在显示 SKILL.md
| name | dotnet-cheatsheet |
| description | Guidance for modern .NET code patterns and libraries. Use when working with dotnet cheatsheet. |
| license | MIT |
| metadata | {"displayName":".NET Cheatsheet (Modern)","author":"Tyler-R-Kendrick"} |
| references | [{"title":".NET Documentation on Microsoft Learn","url":"https://learn.microsoft.com/dotnet/"},{"title":".NET GitHub Repository","url":"https://github.com/dotnet/runtime"}] |
Use these guidelines to write modern .NET code with testability, reliability, and observability.
System.IO.Abstractions) and test through interfaces.Guard methods for guard clauses and keep them inside type boundaries.record types for DTOs and API contracts.Use primary constructors to declare dependencies once and keep the class concise.
public sealed class CatalogService(TimeProvider timeProvider, ILogger<CatalogService> logger)
{
public Task PublishAsync(ValueString id, CancellationToken ct)
{
logger.LogInformation("Publishing {Id} at {Time}", id, timeProvider.GetUtcNow());
return Task.CompletedTask;
}
}
Why: Static classes are hard to mock and hide dependencies.
Pattern: wrap static calls.
public interface ISystemClock
{
DateTimeOffset UtcNow { get; }
}
public sealed class SystemClock : ISystemClock
{
public DateTimeOffset UtcNow => DateTimeOffset.UtcNow;
}
Use TimeProvider so time can be mocked and centrally controlled.
public sealed class BillingService
{
private readonly TimeProvider _timeProvider;
public BillingService(TimeProvider timeProvider)
{
_timeProvider = timeProvider;
}
public DateTimeOffset GetChargeTimestamp() => _timeProvider.GetUtcNow();
}
builder.Services.AddSingleton(TimeProvider.System);
Define explicit types that can only represent valid values. Use these in APIs to avoid null/whitespace checks.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using CommunityToolkit.Diagnostics;
[DebuggerDisplay("{Value}")]
public readonly record struct ValueString
{
public string Value { get; }
private ValueString(string value)
{
// Guard clauses remain inside the type boundary.
Value = Guard.IsNotNullOrWhiteSpace(value);
}
public static ValueString Parse(string value) => new(value);
public static bool TryParse(
[NotNullWhen(true)] string? value,
[NotNullWhen(true)] out ValueString result)
{
if (string.IsNullOrWhiteSpace(value))
{
result = default;
return false;
}
result = new ValueString(value);
return true;
}
() => .Value;
=> Parse();
=> Value;
}
Guidance:
ValueString).Guard for consistency and better static analysis hints.Use IsolatedStorageFile to store per-user or per-application data securely.
using System.IO;
using System.IO.IsolatedStorage;
public interface IUserSettingsStore
{
Task SaveAsync(string key, string value, CancellationToken token);
Task<string?> ReadAsync(string key, CancellationToken token);
}
public sealed class IsolatedStorageUserSettingsStore : IUserSettingsStore
{
public async Task SaveAsync(string key, string value, CancellationToken token)
{
using var store = IsolatedStorageFile.GetUserStoreForAssembly();
using var stream = new IsolatedStorageFileStream(key, FileMode.Create, store);
using var writer = new StreamWriter(stream);
await writer.WriteAsync(value.AsMemory(), token);
}
public async Task<string?> ReadAsync(string key, CancellationToken token)
{
using var store = IsolatedStorageFile.GetUserStoreForAssembly();
if (!store.FileExists(key))
{
return null;
}
using var stream = new IsolatedStorageFileStream(key, FileMode.Open, store);
reader = StreamReader(stream);
reader.ReadToEndAsync(token);
}
}
Use AppContext switches to toggle compatibility and feature flags.
if (AppContext.TryGetSwitch("MyApp.DisableLegacyBehavior", out var disabled) && disabled)
{
// Legacy behavior is disabled.
}
Use resource files (.resx) with IStringLocalizer or ResourceManager.
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
public sealed class MyService
{
private readonly IStringLocalizer<MyService> _localizer;
public MyService(IStringLocalizer<MyService> localizer)
{
_localizer = localizer;
}
public string GetMessage() => _localizer["WelcomeMessage"];
}
Use IChangeToken and ChangeToken for configuration or file change notifications.
using Microsoft.Extensions.Primitives;
ChangeToken.OnChange(
() => configuration.GetReloadToken(),
() => logger.LogInformation("Configuration reloaded"));
Add service discovery for HTTP clients.
builder.Services.AddServiceDiscovery();
builder.Services.AddHttpClient("catalog")
.AddServiceDiscovery();
Use the resilience pipeline for retries, timeouts, and hedging.
builder.Services.AddResiliencePipeline("catalog", pipeline =>
{
pipeline.AddRetry(new() { MaxRetryAttempts = 3 });
pipeline.AddTimeout(TimeSpan.FromSeconds(5));
});
builder.Services.AddHttpClient("catalog")
.AddResilienceHandler("catalog");
Use the Host or WebApplication builder for consistent setup.
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<Worker>();
using var host = builder.Build();
await host.RunAsync();
Guidance:
Program.cs instead of a Main method.Use ILogger with the LoggerMessage source-generation pattern. Add conditional compilation symbols per log level to remove calls when disabled.
using System.Diagnostics;
using Microsoft.Extensions.Logging;
public static partial class Log
{
[LoggerMessage(EventId = 1001, Level = LogLevel.Information, Message = "Processed order {OrderId}")]
public static partial void OrderProcessed(ILogger logger, string orderId);
[LoggerMessage(EventId = 2001, Level = LogLevel.Debug, Message = "Raw payload: {Payload}")]
[Conditional("LOG_DEBUG")]
public static partial void PayloadDebug(ILogger logger, string payload);
[LoggerMessage(EventId = 3001, Level = LogLevel.Trace, Message = "Trace state: {State}")]
[Conditional("LOG_TRACE")]
public static partial void TraceState(ILogger logger, string state);
}
Configure logging for all levels in configuration.
{
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
Guidance:
LOG_TRACE, LOG_DEBUG, LOG_INFORMATION in build configs to remove calls at compile time.Use IConfiguration and options binding.
builder.Services.Configure<MyOptions>(builder.Configuration.GetSection("MyOptions"));
Register services with lifetimes that match behavior.
builder.Services.AddSingleton<ISystemClock, SystemClock>();
builder.Services.AddScoped<IMyService, MyService>();
builder.Services.AddTransient<IUserSettingsStore, IsolatedStorageUserSettingsStore>();
Guidance:
Program.cs.public static class ServiceCollectionExtensions
{
public static IServiceCollection AddAppServices(this IServiceCollection services)
{
services.AddSingleton<ISystemClock, SystemClock>();
services.AddScoped<IMyService, MyService>();
services.AddTransient<IUserSettingsStore, IsolatedStorageUserSettingsStore>();
return services;
}
}
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddAppServices();
Defaults:
DbContext per request.Official framework defaults to mention in app architecture:
For details and examples, use the library-specific skills for each framework.
Eventing defaults:
MediatR:
For details and examples, use the library-specific skills for eventing and MediatR.
Defaults:
Microsoft.Extensions.AI for provider-agnostic abstractions and DI-friendly clients.Azure.AI.Inference for Azure-hosted model access; avoid provider-specific SDKs unless required.a2a and mcp packages for agent-to-agent and model context protocol integrations.For details and examples, use the AI library-specific skills.
Use ASP.NET Core Identity with Identity API endpoints for modern minimal APIs. Rely on UserManager and SignInManager and avoid custom password handling.
For details and examples, use the ASP.NET Core Identity skill.
Use System.IO.Abstractions or your own interfaces around IO.
For details and examples, use the System.IO.Abstractions skill.
Use IFileProvider APIs for abstracted file access (physical, embedded, or composite sources).
For details and examples, use the File Provider skill.
System.IO.Pipelines for high-throughput streaming and parsing.Channel<T> for producer/consumer queues and backpressure.IAsyncEnumerable<T> for streaming data in async flows.For details and examples, use the System.IO.Pipelines, Channels, and IAsyncEnumerable skills.
Use Rx for event streams, UI events, and composition of asynchronous signals.
For details and examples, use the Reactive Extensions skill.
Use .NET 10 file-based apps with file-level directives for SDKs, packages, and properties.
#!/usr/bin/dotnet run
#:sdk Microsoft.NET.Sdk
#:package Humanizer@2.14.1
#:property LangVersion preview
using Humanizer;
var dotNet9Released = DateTimeOffset.Parse("2024-12-03");
var since = DateTimeOffset.Now - dotNet9Released;
Console.WriteLine($"It has been {since.Humanize()} since .NET 9 was released.");
Guidance:
dotnet run app.cs.chmod +x app.cs and run ./app.cs.dotnet project convert app.cs.Use compliance extensions for data classification and policy enforcement.
builder.Services.AddCompliance();
Use IMemoryCache or distributed caching abstractions.
builder.Services.AddMemoryCache();
Configure cultures and localization at host startup.
builder.Services.AddLocalization();
var app = builder.Build();
var supportedCultures = new[] { "en-US", "fr-FR" };
var localizationOptions = new RequestLocalizationOptions()
.SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(localizationOptions);
Use when producing agent/LLM evals, synthetic simulation data, or self-improvement pipelines for prompts, code, skills, agents, harnesses, and workflows. Covers AgentEvals/AgentV, Agent Skills evals, ASSERT, GEPA, Trace, VISTA, Agent Lightning, SkillOpt, Simula-style data design, progressive disclosure, deterministic workspaces, and release evidence. USE FOR: eval creation, EVAL.yaml, AgentEvals, AgentV, evals.json, ASSERT, judge-traces, behavior taxonomy, judges, graders, rubrics, synthetic data, simulation data, Simula, QDC, source-grounded generation, prompt optimization, agent improvement, skill improvement, harness hardening, progressive disclosure, deterministic workflows, GEPA, Trace, VISTA, Agent Lightning, SkillOpt DO NOT USE FOR: ordinary unit/integration tests without AI quality criteria (use testing), refactoring without eval or trace feedback (use refactor), generic Agent Skills packaging without eval or improvement work (use agent-skills)
Use when working with AI agent protocols, standards, interoperability specifications, evaluation contracts, synthetic simulation data, improvement pipelines, and agent steering workflows. Covers MCP, A2A, ACP, Agent Skills, AGENTS.md, ADL, Improve, x402, AP2, MCP Apps, cagent, and learn. USE FOR: agent protocol selection, comparing MCP vs A2A vs ACP, understanding agent standards ecosystem, choosing payment protocols, choosing eval standards, choosing improvement techniques, choosing synthetic data simulation techniques, steering from user feedback DO NOT USE FOR: specific protocol, eval, or improvement implementation details (use the sub-skills: mcp, a2a, acp, improve, learn, x402, etc.)
Use when a user corrects, rejects, edits, or redirects an LLM/agent response and the correction should become a reusable reasoning strategy. Converts feedback into generalized learnings for ~/.agents/STEERING.md with linked RDF/Turtle evidence. USE FOR: user corrections, preference feedback, rejected agent behavior, reasoning strategy updates, steering file maintenance DO NOT USE FOR: storing task facts (use memory), ordinary skill authoring (use agent-skills), project instruction files unrelated to feedback (use agents-md)