如何自定义C# Attribute
要自定义一个C# Attribute,可以依照以下步骤进行:
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAttribute : Attribute
{
public string Name { get; }
public CustomAttribute(string name)
{
Name = name;
}
}
定义一个AttributeUsage特性来指定你的Attribute可以利用到哪些地方,比如类、方法等。在上面的例子中,我们定义了CustomAttribute可以利用到类和方法上。
在需要使用自定义Attribute的地方,直接在类还是方法上使用你定义的Attribute类。
[CustomAttribute("Example")]
public class MyClass
{
[CustomAttribute("Method")]
public void MyMethod()
{
// do something
}
}
// 获得类上的自定义Attribute
CustomAttribute classAttribute = (CustomAttribute)Attribute.GetCustomAttribute(typeof(MyClass), typeof(CustomAttribute));
Console.WriteLine(classAttribute.Name);
// 获得方法上的自定义Attribute
CustomAttribute methodAttribute = (CustomAttribute)Attribute.GetCustomAttribute(typeof(MyClass).GetMethod("MyMethod"), typeof(CustomAttribute));
Console.WriteLine(methodAttribute.Name);
通过以上步骤,你就能够自定义一个C# Attribute,并在需要的地方使用它。
tiktok粉丝购买:https://www.smmfensi.com/
TOP