温馨提示×

C#特性AttributeUsage怎么使用

c#
小亿
84
2024-03-18 19:44:40
栏目: 编程语言

在C#中,AttributeUsage特性用于指定自定义属性可以应用于哪些程序元素。它有三个参数:

  1. ValidOn:指定自定义属性可以应用于哪些程序元素,如类、方法、属性等。可以使用多个值,用逗号分隔。
  2. AllowMultiple:指定是否允许在同一个程序元素上多次应用该自定义属性。默认值为false。
  3. Inherited:指定是否允许派生类继承该自定义属性。默认值为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特性只能应用于类,并且不允许派生类继承该特性。当实例化MyClass类时,会输出"MyAttribute constructor"。

0