【发布时间】:2013-05-15 19:30:20
【问题描述】:
在删除一些过时的代码时,我遇到了一个意想不到的场景,在下面重新创建:
class Program
{
static void Main(string[] args)
{
ViableMethod();
Console.WriteLine("");
SoftDeprecatedMethod();//Compiler warning
//HardDeprecatedMethod();//Can't call that from here, compiler error
Console.ReadKey(true);
}
public static void ViableMethod ()
{
Console.WriteLine("ViableMethod, calls SoftDeprecatedMethod");
SoftDeprecatedMethod();//Compiler warning
//HardDeprecatedMethod();//Can't call that from here, compiler error
}
[Obsolete("soft", false)]
public static void SoftDeprecatedMethod()
{
Console.WriteLine("SoftDeprecatedMethod, calls HardDeprecatedMethod");
HardDeprecatedMethod();
}
[Obsolete("hard", true)]
public static void HardDeprecatedMethod()
{
Console.WriteLine("HardDeprecatedMethod");
}
}
根据输出,似乎允许使用警告弃用的函数调用因错误而弃用的函数并且代码将执行。
我的期望是我会看到一个编译器错误,抱怨不允许从 SoftDeprecatedMethod() 调用 HardDeprecatedMethod()。
观察到的行为对我来说似乎很奇怪。
有谁知道这是否是期望的行为(如果是,为什么),或者这可能是 [Obsolete] 属性实现中的缺陷吗?
【问题讨论】:
-
好问题。我怀疑这是故意的(因为它有时可以使弃用过程更加顺利),但它没有包含在语言规范中。
-
@JonSkeet 当我读到这个问题时,我的第一个想法是“天哪,为什么 Jon 没有回答这个问题?”然后我读了你的评论。那有点……出乎意料:-)
-
另外请注意,
[Obsolete]是 Attribute,而不是关键字。如果您愿意,我们非常欢迎您将变量/类命名为“过时”。 -
@Krumelur:是的,我真的希望这是一个容易回答的问题,只需引用规范即可。后来发现不是……
标签: c# .net attributes