简体   繁体   中英

Making a third-party method [Obsolete]

If I want to declare a method in my code as deprecated / obsolete, I can add the [Obsolete] attribute to it and make the compiler emit a warning (or error) whenever the method is used.

Is it possible to achieve a similar effect for third-party methods (such as System.Console.WriteLine )? Obviously, I cannot add the attribute since I do not control the code. But maybe there is some other trick available in .NET or Visual Studio?

I'm preferably looking for an "out of the box" solution that does not require something like writing my own post-build script that manually parses the code.

With Visual Studio 2015 you can create live Code Analyzers that can provide custom design-time checking for virtually anything. A good tutorial is available here . These usually live as part of the solution, so so they will "follow it around" no matter where it is compiled.

Code analyzers can can raise compile time errors or warnings, and can even present a UI to automatically correct the issue. They can be VERY powerful, but writing one of these can be fairly complex depending on what you need.

A similar feature exists for previous versions of Visual Studio (2010+). It isn't as well integrated, but might work for you.

You can do that by creating custom code inspection rules in ReSharper.

Go to ReSharper / Options / Code Inspection / Custom Pattern / Add Pattern, write a pattern that matches the deprecated method call and select an inspection severity such as "suggestion" or "warning". You may also write a replacement pattern that can be applied via quick fixes.

Example :

一种自定义模式的示例

In this example, the System.Console was misused for logging and should be replaced by proper log4net calls.

Another option for ReSharper users: ExternalAnnotations .

Here is an example of adding the annotations for Selenium's WebDriver.dll :

  1. Create ExternalAnnotations folder beside *.csproj of the target project.
  2. Inside the folder create WebDriver.xml :
     <?xml version="1.0" encoding="utf-8" ?> <assembly name="WebDriver"> <member name="M:OpenQA.Selenium.INavigation.GoToUrl(System.String)"> <attribute ctor="M:System.ObsoleteAttribute.#ctor(System.String,System.Boolean)"> <argument>Use different overload of this method.</argument> <argument>true</argument> </attribute> </member>
  3. Reload the solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM