[MyCustomAttribute("Example")] 中括号写在类前,表示此类具有此特性。
”property” 译为“属性
Attribute用特性描述
using System;// 定义一个自定义特性
public class MyCustomAttribute : Attribute
{public string Value { get; set; }public MyCustomAttribute(string value){Value = value;}
}// 应用自定义特性到类上
[MyCustomAttribute("Example")]
public class MyClass
{
}class Program
{static void Main(){// 检查特性是否存在var attributes = typeof(MyClass).GetCustomAttributes(typeof(MyCustomAttribute), false);if (attributes.Length > 0){var myAttribute = (MyCustomAttribute)attributes[0];Console.WriteLine(myAttribute.Value); // 输出: Example}}
}
参考:
https://www.cnblogs.com/yangxx-1990/p/10919612.html