1、先创建一些特性以及一个示例类
//应用的目标类型:类,属性,或者其他,是否对同一个目标进行多次应用 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] class DoseInterstingThingAttribute : Attribute { public int HowManyTimes { get; private set; } public string WhatDoseItDo { get; set; } public DoseInterstingThingAttribute(int howManyTimes) { HowManyTimes = howManyTimes; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] class DataBaseTypeAttribute : Attribute { public string DataTypeName { get; set; } public int MaxConnectiCount { get; set; } public DataBaseTypeAttribute(string dataTypeName) { DataTypeName = dataTypeName; } } [AttributeUsage(AttributeTargets.Property,AllowMultiple =false)] class DataAttribute : Attribute { public bool IsPrimaryKey { get; set; } } [DataBaseType("Mysql", MaxConnectiCount = 1000)] [DoseInterstingThing(1000)] public class DecoratedClass { [Data(IsPrimaryKey =false)] public int Code { get; set; } public string Name { get; set; } }
2、Main方法中输出
static void Main(string[] args) { #region 特性使用 Type classType = typeof(DecoratedClass); object[] customAttributes = classType.GetCustomAttributes(true); foreach (var customAttribute in customAttributes) { Console.WriteLine($"Attribute of type {customAttribute} found."); DoseInterstingThingAttribute interstingThingAttribute = customAttribute as DoseInterstingThingAttribute; if (interstingThingAttribute != null) { Console.WriteLine($"This class does {interstingThingAttribute.WhatDoseItDo} x{interstingThingAttribute.HowManyTimes}"); } DataBaseTypeAttribute dataBaseTypeAttribute = customAttribute as DataBaseTypeAttribute; if (dataBaseTypeAttribute != null) { Console.WriteLine($"This class does {dataBaseTypeAttribute.DataTypeName}"); } } PropertyInfo[] propertyInfo = classType.GetProperties(); foreach (var property in propertyInfo) { object[] customAttributes_Propertys = classType.GetProperty(property.Name).GetCustomAttributes(true); foreach (var customAttributes_Property in customAttributes_Propertys) { Console.WriteLine((DataAttribute)customAttributes_Property==null? $"{property.Name}不存在Data特性": ((DataAttribute)customAttributes_Property).IsPrimaryKey.ToString()); } } #endregion }
标签:set,get,C#,创建,AttributeTargets,特性,class,customAttributes,public From: https://www.cnblogs.com/icarec/p/17640304.html