AttributeUsage 是一个 C# 属性,用于指定自定义属性在代码中的使用方式。它位于 System.ComponentModel 命名空间中。通过使用 AttributeUsage,您可以控制属性的重复使用、继承和应用于哪些代码元素(如类、方法、属性等)。
以下是如何使用 AttributeUsage 的示例:
MyCustomAttribute 的属性:using System; [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public class MyCustomAttribute : Attribute { public string MyProperty { get; set; } public MyCustomAttribute(string myProperty) { MyProperty = myProperty; } } 在这个例子中,我们使用 AttributeUsage 指定了以下选项:
AttributeTargets.Method:表示该属性只能应用于方法。Inherited = false:表示该属性不可继承。AllowMultiple = true:表示该属性可以应用于同一个元素多次。public class MyClass { [MyCustom("Hello, World!")] public void MyMethod() { Console.WriteLine("This is my method."); } } 在这个例子中,我们将 MyCustomAttribute 应用于 MyMethod 方法。由于我们在 AttributeUsage 中设置了 AllowMultiple = true,因此可以在同一个类中的其他方法上多次使用此属性。
using System; using System.Reflection; public class Program { public static void Main() { Type type = typeof(MyClass); MethodInfo method = type.GetMethod("MyMethod"); if (method.IsDefined(typeof(MyCustomAttribute), false)) { var attributes = method.GetCustomAttributes(typeof(MyCustomAttribute), false) as MyCustomAttribute[]; foreach (var attribute in attributes) { Console.WriteLine($"MyCustomAttribute value: {attribute.MyProperty}"); } } } } 在这个例子中,我们使用反射获取 MyClass 类的 MyMethod 方法的信息,并检查它是否定义了 MyCustomAttribute。如果定义了该属性,我们遍历属性数组并输出属性值。