在删除一些过时的代码时,我遇到了一个意想不到的场景,重新创建如下:
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]属性实现中的一个缺陷?
发布于 2013-05-16 04:58:50
事实上,情况正好相反:它表明C#编译器很聪明,并且非常清楚地使用了用Obsolete标记的方法。
假设您将此代码作为类库中的公共API提供给Bob。
HardDeprecatedMethod,他应该得到一个编译时错误;并且他将会。SoftDeprecatedMethod anywhere,从现在开始,他应该被警告这一点,但他的代码应该仍然可以工作;它将会工作。这样你就能得到你想要的东西了!
https://stackoverflow.com/questions/16573450
复制相似问题