How do I mark a method as obsolete or deprecated?

如何将过时的方法标记为废弃或使用C#废弃?


The shortest way is by adding the ObsoleteAttribute as an attribute to the method. Make sure to include an appropriate explanation:

[Obsolete("Method1 is deprecated, please use Method2 instead.")]
public void Method1()
{ … }

You can also cause the compilation to fail, treating the usage of the method as an error instead of warning, if the method is called from somewhere in code like this:

[Obsolete("Method1 is deprecated, please use Method2 instead.", true)]

To mark as obsolete with a warning:

[Obsolete]
private static void SomeMethod()

You get a warning when you use it:

And with IntelliSense:

If you want a message:

[Obsolete("My message")]
private static void SomeMethod()

Here's the IntelliSense tool tip:

智能感知显示过时的消息

Finally if you want the usage to be flagged as an error:

[Obsolete("My message", true)]
private static void SomeMethod()

When used this is what you get:

Note: Use the message to tell people what they should use instead, not why it is obsolete.


Add an annotation to the method using the keyword Obsolete. Message argument is optional but a good idea to communicate why the item is now obsolete and/or what to use instead. Example:

[System.Obsolete("use myMethodB instead")]
void myMethodA()
链接地址: http://www.djcxy.com/p/64326.html

上一篇: XML序列化用于集合类型

下一篇: 如何将方法标记为过时或弃用?