Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Obsolete Attributes ใน C# (ทำเครื่องหมาย Method ล้าสมัย)

ถ้า Method มี Obsolete Attribute Compiler จะแจ้ง Warning (หรือ Error) หลัง Compile

ใช้เมื่อมี Method ใหม่ แต่อยากเก็บ Method เก่าไว้ แจ้งให้ใช้ Method ใหม่แทน

ตัวอย่าง

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(); // จะเกิด Error
    }
}

ผลลัพธ์ (Error เพราะ iserror = true):

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