问题
Is it possible to detect unreachable code or other built in compile warnings using Roslyn?
private void DoSomething()
{
string a = "TEST";
throw new Exception("Why would I throw an exception here?");
a = "This will never be reached"; //this is a compile time warning for unreachable code...Can I detect it?
}
I've tried examining the node properties in Semantic and Syntax methods but didn't see any issues or warning collections.
回答1:
You can discover this using the semantic model's AnalyzeRegionControlFlow method. You call this passing in a text span that correspond to the statements you are interested in. AnalyzeRegionControlFlow will return you a data structure that has a property RegionEndPointIsReachable, it will also tell you all the statements that either jump into or out of the region.
If you want to know how to find the actual diagnostics that the compiler would report you need to use the GetDiagnostics method on the semantic model.
来源:https://stackoverflow.com/questions/10233506/is-it-possible-to-detect-unreachable-code-or-other-built-in-compile-warnings-usi