Csharp/CSharp Tutorial/Attribute/Obsolete Attribute

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Demonstrate the Obsolete attribute.

<source lang="csharp">using System;

class MainClass {

 [Obsolete("Use myMeth2, instead.")]  
 static int myMethod(int a, int b) { 
   return 0; 
 } 

 // Improved version of myMethod. 
 static int myMethod2(int a, int b) { 
   return 1; 
 } 

 public static void Main() { 
  // warning displayed for this 
   Console.WriteLine("4 / 3 is " + myMethod(4, 3)); 

  // no warning here 
   Console.WriteLine("4 / 3 is " + myMethod2(4, 3));  
 } 

}</source>

4 / 3 is 0
4 / 3 is 1

Obsolete attribute: throw an error if the user tries to use Method2

<source lang="csharp">using System; class MainClass {

 [Obsolete("Method2 has been replaced by NewMethod2", true)]
 public static int Method2()
 {
   return 2;
 }
 public static void Main() 
 {
   Console.WriteLine(Method2());
 }

}</source>

ObsoleteattributethrowanerroriftheusertriestouseMethod2.cs(16,21): error CS0619:
        "MainClass.Method2()" is obsolete: "Method2 has been replaced by NewMethod2"

Obsolete attribute: warn the user that Method is obsolete

<source lang="csharp">using System; class MainClass {

 [Obsolete("Method1 has been replaced by NewMethod1", false)]
 public static int Method1()
 {
   return 1;
 }
 public static void Main() 
 {
   Console.WriteLine(Method1());
 }

}</source>

ObsoleteattributewarntheuserthatMethodisobsolete.cs(18,21): warning CS0618: "MainClass.Method1()" is
        obsolete: "Method1 has been replaced by NewMethod1"
1

The Obsolete Attribute

  1. The Obsolete attribute is short for System.ObsoleteAttribute
  2. The Obsolete attribute lets you mark a program element as obsolete.

It has this general form:


<source lang="csharp">[Obsolete("message")]</source>

Using ObsoleteAttribute

<source lang="csharp">using System; class Program {

 public static void Main()
 {
     ObsoleteMethod();
 }
 [Obsolete]
 public static void ObsoleteMethod()
 {
 }

}</source>