温馨提示×

C#的attributeusage怎么使用

小亿
103
2023-07-11 17:08:50
栏目: 编程语言

AttributeUsage是一个特性,用于指定如何使用自定义特性。在C#中,可以通过AttributeUsage特性来指定自定义特性可以应用的目标类型和使用方式。

以下是AttributeUsage特性的使用示例:

using System;
// 自定义特性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class CustomAttribute : Attribute
{
public string Name { get; set; }
public CustomAttribute(string name)
{
Name = name;
}
}
// 使用自定义特性
[Custom("ClassAttribute")]
public class MyClass
{
[Custom("MethodAttribute")]
public void MyMethod()
{
Console.WriteLine("Hello, World!");
}
}
class Program
{
static void Main(string[] args)
{
// 获取类上的特性
var classAttributes = typeof(MyClass).GetCustomAttributes(typeof(CustomAttribute), false);
foreach (CustomAttribute attribute in classAttributes)
{
Console.WriteLine(attribute.Name);
}
// 获取方法上的特性
var methodAttributes = typeof(MyClass).GetMethod("MyMethod").GetCustomAttributes(typeof(CustomAttribute), false);
foreach (CustomAttribute attribute in methodAttributes)
{
Console.WriteLine(attribute.Name);
}
}
}

在上面的示例中,我们定义了一个CustomAttribute特性,并使用AttributeUsage特性指定了该特性可以应用于类和方法。然后,在MyClass类和MyMethod方法上应用了CustomAttribute特性。

在Main方法中,我们使用反射获取了MyClass类和MyMethod方法上的CustomAttribute特性,并输出了特性的Name属性值。

请注意,AttributeUsage特性的构造函数有两个参数,第一个参数用于指定特性可以应用的目标类型(可以是一个或多个),第二个参数用于指定是否允许多次应用该特性。在示例中,我们指定了CustomAttribute特性可以应用于类和方法,并允许多次应用。

0