- Roslyn Cookbook
- Manish Vasani
- 282字
- 2021-07-15 17:07:30
How to do it...
- In Solution Explorer, double-click on Resources.resx file in CSharpAnalyzers project to open the resource file in the resource editor.
- Replace the existing resource strings for AnalyzerDescription, AnalyzerMessageFormat and AnalyzerTitle with new strings:

- 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);
}
- Click on Ctrl + F5 to start a new Visual Studio instance with the analyzer enabled.
- 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
{
}
}
}
}
- Verify the compiler reported diagnostic CS0542 in the error list: 'NestedClass': member names cannot be the same as their enclosing type.
- Change the class library code to following:
namespace ClassLibrary
{
public class OuterClass
{
public class NestedClass
{
public class InnerClass
{
public class NestedClass
{
}
}
}
}
}
- Verify that CS0542 isn t reported anymore, but the error list has our analyzer diagnostic:

- 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.
推薦閱讀
- Python編程自學手冊
- ClickHouse性能之巔:從架構設計解讀性能之謎
- 深入理解Bootstrap
- 新一代通用視頻編碼H.266/VVC:原理、標準與實現
- Python編程完全入門教程
- Getting Started with SQL Server 2012 Cube Development
- 網絡爬蟲原理與實踐:基于C#語言
- iOS編程基礎:Swift、Xcode和Cocoa入門指南
- Creating Stunning Dashboards with QlikView
- Instant PHP Web Scraping
- Android傳感器開發與智能設備案例實戰
- Building Slack Bots
- 零基礎輕松學C++:青少年趣味編程(全彩版)
- Practical Predictive Analytics
- Python第三方庫開發應用實戰