- 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.
推薦閱讀
- C/C++算法從菜鳥(niǎo)到達(dá)人
- CentOS 7 Linux Server Cookbook(Second Edition)
- Rake Task Management Essentials
- Machine Learning with R Cookbook(Second Edition)
- 網(wǎng)頁(yè)設(shè)計(jì)與制作教程(HTML+CSS+JavaScript)(第2版)
- Practical Windows Forensics
- PLC編程及應(yīng)用實(shí)戰(zhàn)
- Java EE 7 Performance Tuning and Optimization
- 數(shù)據(jù)結(jié)構(gòu)案例教程(C/C++版)
- Learning Unreal Engine Android Game Development
- 案例式C語(yǔ)言程序設(shè)計(jì)實(shí)驗(yàn)指導(dǎo)
- Qt5 C++ GUI Programming Cookbook
- Mudbox 2013 Cookbook
- Penetration Testing with the Bash shell
- Groovy 2 Cookbook