C# 中的过时属性是什么?

csharpprogrammingserver side programming更新于 2025/10/14 9:07:17

如果某个方法具有过时属性,编译器会在编译后在代码中发出警告。

当类中使用新方法时,如果您仍想保留旧方法,可以将其标记为过时,方法是显示一条消息,提示应使用新方法,而不是旧方法。

以下示例展示了如何使用过时属性 −

using System;

public class Demo {
   [Obsolete("不应使用旧方法!请改用新方法", true)]

   static void OldMethod() {
      Console.WriteLine("这是旧方法!");
   }

   static void NewMethod() {
      Console.WriteLine("这是新方法!");
   }

   public static void Main() {
      OldMethod();
   }
}

由于我们上面设置了警告信息,因此将显示以下警告 −

Compilation failed: 1 error(s), 0 warnings
error CS0619: `Demo.OldMethod()' is obsolete: `Old Method shouldn't be used! Use New Method instead'

相关文章