Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Attribute Obsolete (Lỗi thời) trong C#

Nếu phương thức có attribute Obsolete, compiler cảnh báo/báo lỗi sau khi biên dịch.

Khi phương thức mới thay thế phương thức cũ nhưng vẫn muốn giữ phương thức cũ, đánh dấu nó obsolete với thông báo dùng phương thức mới.

Ví dụ

using System;

public class Demo {
    [Obsolete("Old Method shouldn't be used! Use New Method instead", true)]
    static void OldMethod() {
        Console.WriteLine("This is the old method!");
    }
    static void NewMethod() {
        Console.WriteLine("This is the new method!");
    }
    public static void Main() {
        OldMethod(); // Gây lỗi compile
    }
}

Kết quả biên dịch:

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