使用[Obsolete]属性的弃用行为

Goe*_*ine 23 .net c# attributes

在删除一些过时的代码时,我遇到了一个意想不到的情况,重新创建如下:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

基于输出,似乎允许使用警告弃用的函数调用已弃用的函数,并且代码将执行.

我的期望是我会看到编译器错误抱怨不允许调用HardDeprecatedMethod()from SoftDeprecatedMethod().观察到的行为对我来说似乎很奇怪.

有谁知道这是否是所期望的行为(如果是,为什么),或者这可能是[Obsolete]属性实现中的缺陷?

Kav*_*ian 5

实际上它是另一种方式:它表明C#编译器很聪明,并且在使用标记的方法时非常清楚Obsolete.

假设您将此代码作为类库中的公共API提供给Bob.

  1. 你希望Bob调用HardDeprecatedMethod他的代码,他应该得到一个编译时错误; 他会的.

  2. 你希望鲍勃在SoftDeprecatedMethod任何地方打电话,从这时起,他应该被警告,但他的代码应该仍然有效; 它会.

所以你得到你想要的东西!