Visual Studio C#编译器警告无意中将变量分配给自身,但此警告不适用于C#属性,仅适用于变量.如其他问题所述.
但是,如果我为自己分配一个属性,我真的会喜欢类似的东西,可以在编译时警告我.
我目前正在使用Visual Studio 2013,但如果解决方案至少在Visual Studio 2015中有效,我也没关系.另外,我不使用像ReSharper或CodeRush这样的第三方商业插件,所以我更喜欢不使用的解决方案涉及购买东西,但我愿意接受建议.
你知道我怎么能做到这一点?
我非常习惯使用只读公共"检查"属性来构建接收器依赖注入模式来存储接收到的依赖项.
例如,假设一个Foo依赖于ILogger实现的类.该logger实例在构造函数中提供给类,构造函数检查空值并将依赖项存储在名为的实例属性中Logger:
public class Foo
{
public ILogger Logger { get; private set; }
public Foo(ILogger logger)
{
if(logger == null) throw new ArgumentNullException("logger");
this.Logger = logger;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我经常输入错误,将属性分配给自己而不是传递给构造函数的参数.
public class Foo
{
public ILogger Logger { get; private set; }
public Foo(ILogger logger)
{
if(logger == null) throw new ArgumentNullException("logger");
this.Logger = Logger; // <-- This is wrong. Property assigned to itself.
}
}
Run Code Online (Sandbox Code Playgroud)
当然,我总是在测试和调试时最终发现这些错误,但它已经困扰了我几次,我不想再浪费时间在这样一个愚蠢的错误中.
有什么建议?
这是VS2015实时代码分析器的完美情况.您可以编写一个基本分析器,检查属性是否已分配给自身并创建错误.
这是一个非常好的教程,我很久以前就帮助你开始编写一个,它们不是很难做到:" C#和Visual Basic - 使用Roslyn为你的API编写一个实时代码分析器 "
更新:我有一些空闲时间,所以我写了一个分析器,它做到了.
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SelfAssignmentAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "SelfAssignment";
private static readonly LocalizableString Title = "Do not do self assignment";
private static readonly LocalizableString MessageFormat = "The variable '{0}' is assigned to itself";
private static readonly LocalizableString Description = "A variable assignment to itself is likely an indication of a larger error.";
private const string Category = "Correctness";
private static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.SimpleAssignmentExpression);
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var assignmentExpr = (AssignmentExpressionSyntax)context.Node;
var right = context.SemanticModel.GetSymbolInfo(assignmentExpr.Right);
var left = context.SemanticModel.GetSymbolInfo(assignmentExpr.Left);
if (!right.Equals(left))
return;
var diagnostic = Diagnostic.Create(Rule, assignmentExpr.GetLocation(), assignmentExpr.Left.ToString());
context.ReportDiagnostic(diagnostic);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以进行优化,可以在不调用的情况下排除情况GetSymbolInfo(例如,检查左侧和右侧的文本以查看它们是否匹配)但我将其作为练习留给您.
编辑:
Visual Studio 2015中的分析器:
| 归档时间: |
|
| 查看次数: |
474 次 |
| 最近记录: |