You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET6项目中如何定义规则集,禁用特定属性触发编译错误?

项目级别禁止使用特定属性(如DateTime.Now)并触发编译错误的实现方法

既然你在用.NET 6 Minimal API + Visual Studio 2022,还有Resharper授权,完全可以实现这个需求,下面给你几个靠谱的方案:

方案一:用Resharper自定义规则(最快实现)

  1. 打开Visual Studio,依次点 Resharper > Options > Code Inspection > Custom Patterns
  2. 点Add Pattern,选Search pattern,在输入框里填DateTime.Now,上下文选「Expression」就行
  3. 切到Action标签页,把严重级别改成Error,顺便写个提示语,比如「禁止直接用DateTime.Now,改用注入的时间服务」
  4. 保存规则后,去Resharper > Options > Code Inspection > Inspection Severity里确认这个规则已经应用到当前项目
  5. 开着Resharper的即时分析,写代码的时候会实时标红报错,要是开了Resharper的编译检查,编译时也会直接卡壳,彻底拦下来

方案二:自定义Roslyn分析器(编译级强制,不依赖Resharper)

如果想要不依赖Resharper,从编译层面硬禁止,就自己写个Roslyn分析器:

  1. 新建一个「Class Library (.NET Standard)」项目,装Microsoft.CodeAnalysis.Analyzers和Microsoft.CodeAnalysis.CSharp这两个NuGet包
  2. 写分析器代码,检测DateTime.Now的调用并标记为错误:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ForbidDateTimeNowAnalyzer : DiagnosticAnalyzer
{
    public const string DiagnosticId = "ForbidDateTimeNow";
    private const string Title = "禁止使用DateTime.Now";
    private const string MessageFormat = "别直接用DateTime.now,改用注入的时间服务";
    private const string Category = "Usage";

    private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
        DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Error, isEnabledByDefault: true);

    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);

    public override void Initialize(AnalysisContext context)
    {
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
        context.EnableConcurrentExecution();
        context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.SimpleMemberAccessExpression);
    }

    private void AnalyzeNode(SyntaxNodeAnalysisContext context)
    {
        var memberAccess = (MemberAccessExpressionSyntax)context.Node;
        if (memberAccess.Name.Identifier.Text == "Now" &&
            memberAccess.Expression is IdentifierNameSyntax identifier &&
            identifier.Identifier.Text == "DateTime")
        {
            var diagnostic = Diagnostic.Create(Rule, memberAccess.GetLocation());
            context.ReportDiagnostic(diagnostic);
        }
    }
}
  1. 把这个分析器项目打成NuGet包,或者直接引用到你的Minimal API项目里,之后只要代码里出现DateTime.Now,编译时就直接报错,根本过不了

方案三:配合.editorconfig统一配置

不管用Resharper还是Roslyn分析器,都可以用.editorconfig来统一管理规则:

  • 在项目根目录建个.editorconfig文件
  • 如果是Resharper的自定义规则,加这行(规则名要和你之前创建的对应):
[*.cs]
resharper_custom_pattern_forbid_datetime_now = error
  • 如果是用Roslyn分析器,就加:
[*.cs]
dotnet_diagnostic.ForbidDateTimeNow.severity = error

内容的提问来源于stack exchange,提问作者Darshit Gandhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 12:55:31