溫馨提示×

C#特性AttributeUsage怎么使用

c#
小億
87
2024-03-18 19:44:40
欄目: 編程語言

在C#中,AttributeUsage特性用于指定自定義屬性可以應(yīng)用于哪些程序元素。它有三個參數(shù):

  1. ValidOn:指定自定義屬性可以應(yīng)用于哪些程序元素,如類、方法、屬性等??梢允褂枚鄠€值,用逗號分隔。
  2. AllowMultiple:指定是否允許在同一個程序元素上多次應(yīng)用該自定義屬性。默認(rèn)值為false。
  3. Inherited:指定是否允許派生類繼承該自定義屬性。默認(rèn)值為false。

下面是一個使用AttributeUsage特性的示例:

using System;

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class MyAttribute : Attribute
{
    public MyAttribute()
    {
        Console.WriteLine("MyAttribute constructor");
    }
}

[My]
public class MyClass
{
    public void MyMethod()
    {
        Console.WriteLine("MyMethod");
    }
}

class Program
{
    static void Main()
    {
        MyClass myClass = new MyClass();
    }
}

在這個示例中,MyAttribute特性只能應(yīng)用于類,并且不允許派生類繼承該特性。當(dāng)實例化MyClass類時,會輸出"MyAttribute constructor"。

0