官术网_书友最值得收藏!

How to do it...

  1. In Solution Explorer, double-click on Resources.resx file in CSharpAnalyzers project to open the resource file in the resource editor.
  2. Replace the existing resource strings for AnalyzerDescription, AnalyzerMessageFormat and AnalyzerTitle with new strings:
  1. Replace the Initialize method implementation with the following:
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(symbolContext =>
{
var symbolName = symbolContext.Symbol.Name;

// Skip the immediate containing type, CS0542 already covers this case.
var outerType = symbolContext.Symbol.ContainingType?.ContainingType;
while (outerType != null)
{
// Check if the current outer type has the same name as the given member.
if (symbolName.Equals(outerType.Name))
{
// For all such symbols, report a diagnostic.
var diagnostic = Diagnostic.Create(Rule, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name);
symbolContext.ReportDiagnostic(diagnostic);
return;
}

outerType = outerType.ContainingType;
}
},
SymbolKind.NamedType,
SymbolKind.Method,
SymbolKind.Field,
SymbolKind.Event,
SymbolKind.Property);
}
  1. Click on Ctrl + F5 to start a new Visual Studio instance with the analyzer enabled.
  2. In the new Visual Studio instance, create a new C# class library with the following code:
namespace ClassLibrary
{
public class OuterClass
{
public class NestedClass
{
public class NestedClass
{
}
}
}
}
  1. Verify the compiler reported diagnostic CS0542 in the error list: 'NestedClass': member names cannot be the same as their enclosing type.
  2. Change the class library code to following:
namespace ClassLibrary
{
public class OuterClass
{
public class NestedClass
{
public class InnerClass
{
public class NestedClass
{
}
}
}
}
}
  1. Verify that CS0542 isn t reported anymore, but the error list has our analyzer diagnostic:
  1. Replace the innermost type declaration for NestedClass with a field: public int NestedClass, and verify the same analyzer diagnostic is reported. You should get the same diagnostic for other member kinds such as method, property, and events with the same name.
主站蜘蛛池模板: 黎平县| 凌源市| 磐石市| 石屏县| 淅川县| 鄂尔多斯市| 大城县| 雷山县| 乌兰浩特市| 杭锦旗| 乌兰察布市| 黄冈市| 临沂市| 广昌县| 松溪县| 太仆寺旗| 琼结县| 延寿县| 阿巴嘎旗| 罗田县| 金山区| 肃宁县| 女性| 灵石县| 台湾省| 连山| 犍为县| 公安县| 台前县| 万州区| 鹿邑县| 元江| 凤凰县| 邵阳县| 修文县| 遂平县| 彝良县| 措美县| 墨脱县| 三河市| 理塘县|