通知开发人员"请勿使用"方法
时间:2020-03-05 18:43:14 来源:igfitidea点击:
好吧,我知道我们在想什么,"为什么要编写一种我们不希望人们使用的方法?"正确的?
好吧,简而言之,我有一个需要序列化为XML的类。为了使XmlSerializer发挥其魔力,该类必须具有一个默认的空构造函数:
public class MyClass { public MyClass() { // required for xml serialization } }
因此,我需要它,但我不希望人们使用它,那么是否有任何属性可用于将该方法标记为"请勿使用"?
我当时正在考虑使用Obsolete属性(因为这可以停止构建),但这似乎有点"错误",还有其他方法可以这样做,还是我需要继续努力? :)
更新
好的,我接受了基思的回答,因为我内心深处猜测,我完全同意。这就是为什么我首先问这个问题的原因,我不喜欢拥有过时属性的概念。
然而...
仍然存在一个问题,尽管在智能感知中收到通知时,理想情况下,我们想中断构建,所以有什么办法可以做到这一点?也许创建一个自定义属性?
在此创建了更集中的问题。
解决方案
回答
我读了标题,立即想到"过时的属性"。怎么样
/// <summary> /// do not use /// </summary> /// <param name="item">don't pass it anything -- you shouldn't use it.</param> /// <returns>nothing - you shouldn't use it</returns> public bool Include(T item) { ....
回答
ObsoleteAttribute
可能会在情况下起作用,如果使用该方法,我们甚至可能导致构建中断。
由于过时的警告发生在编译时,并且序列化所需的反射发生在运行时,因此标记该方法过时不会破坏序列化,但会警告开发人员该方法不可用。
回答
我们正在寻找的是ObsoleteAttribute
类:
using System; public sealed class App { static void Main() { // The line below causes the compiler to issue a warning: // 'App.SomeDeprecatedMethod()' is obsolete: 'Do not call this method.' SomeDeprecatedMethod(); } // The method below is marked with the ObsoleteAttribute. // Any code that attempts to call this method will get a warning. [Obsolete("Do not call this method.")] private static void SomeDeprecatedMethod() { } }
回答
是的,有。
我写了关于它的博客文章。
这是代码:
标题数量不匹配
代码数量不匹配