Visual Studio 2008 / C# : How to find dead code in

2020-02-08 15:12发布

How do I find dead code in a Visual Studio 2008 C# project? Like unused classes, unused variables or unused resources?

5条回答
等我变得足够好
2楼-- · 2020-02-08 15:49

Shift + F12 in VS is useful for a quick check :)

查看更多
看我几分像从前
3楼-- · 2020-02-08 15:56

A very useful tool for this is the NDepend dependency analysis tool. You can load your Visual Studio project into this, and it will analyse the dependencies of all your assemblies, types and methods. It gives you a wealth of information on the dependenices, including (but in no way limited to!) methods/types that are not used by anything at all.

You can view the dependencies either graphically, or in a list, and can write your own custom dependency queries such as this - a simple CQL query show potentially unused methods :

SELECT 
  METHODS         // Get me a list of methods
WHERE 
  MethodCa == 0   // Where their afferent coupling is zero, (afferent coupling being the number of other methods that call it)

A highly recommended tool.

查看更多
虎瘦雄心在
4楼-- · 2020-02-08 15:57

While I wouldn't recommend this for a large code base you can do a certain amount manually.

If you right click over a method or class and then select "Find Usages" you'll get an output of all places where it's referenced. Obviously this will be empty if it's not used.

For ongoing clean up I'd install ReSharper

查看更多
再贱就再见
5楼-- · 2020-02-08 15:58

Install JetBrains ReSharper which will highlight the unused code for you.

查看更多
叼着烟拽天下
6楼-- · 2020-02-08 16:04

You can try FxCop, which is integrated in Visual Studio 2008 by the name of Code Analysis. You just have to right click the project file and 'Run Code Analysis'.

FxCop is an application that analyzes managed code assemblies (code that targets the .NET Framework common language runtime) and reports information about the assemblies, such as possible design, localization, performance, and security improvements.

The active rules can be configured in the Code Analysis section of the project properties. For example some rules relevant to the case in hand are present in Usage Rules and Performance Rules:

  • CA1801: Review unused parameters.
  • CA1811: Avoid uncalled private code.

And for greater flexibility you also write your own custom rules (Tutorial on writing your own Code Analysis rule).

查看更多
登录 后发表回答