C# 如何将方法标记为已过时或已弃用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1759352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mark a method as obsolete or deprecated?
提问by Chris Ballance
How do I mark a method as obsolete or deprecated using C#?
如何使用C#将方法标记为已过时或已弃用?
采纳答案by Chris Ballance
The shortest way is by adding the ObsoleteAttribute
as an attribute to the method. Make sure to include an appropriate explanation:
最短的方法是将ObsoleteAttribute
作为属性添加到方法。确保包含适当的解释:
[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)]
回答by jchadhowell
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:
使用关键字向方法添加注释Obsolete
。消息参数是可选的,但是一个好主意来传达为什么该项目现在已经过时和/或使用什么来代替。
例子:
[System.Obsolete("use myMethodB instead")]
void myMethodA()
回答by mark_h
To mark as obsolete with a warning:
用警告标记为过时:
[Obsolete]
private static void SomeMethod()
You get a warning when you use it:
使用时会收到警告:
And with IntelliSense:
并使用 IntelliSense:
If you want a message:
如果你想留言:
[Obsolete("My message")]
private static void SomeMethod()
Here's the IntelliSense tool tip:
这是 IntelliSense 工具提示:
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.
注意:使用消息告诉人们他们应该使用什么来代替,而不是为什么它已经过时了。
回答by Sina Lotfi
With ObsoleteAttribute
you can to show the deprecated method.
Obsolete attribute has three constructor:
随着ObsoleteAttribute
你可以显示的方法已过时。Obsolete 属性具有三个构造函数:
[Obsolete]:
is a no parameter constructor and is a default using this attribute.[Obsolete(string message)]:
in this format you can getmessage
of why this method is deprecated.[Obsolete(string message, bool error)]:
in this format message is very explicit buterror
means, in compilation time, compiler must be showing error and cause to fail compiling or not.
[Obsolete]:
是一个无参数构造函数,并且是使用此属性的默认值。[Obsolete(string message)]:
在这种格式中,您可以了解message
为什么不推荐使用此方法。[Obsolete(string message, bool error)]:
这种格式的消息非常明确,但error
意味着在编译时,编译器必须显示错误并导致编译失败。