特性Attibute定义和使用
1.定义特性
[AttributeUsage(AttributeTargets.Class,AllowMultiple = false,Inherited = false)] public class TableNameAttribute:Attribute { private string _tableName; public TableNameAttribute(string tableName) { _tableName = tableName; } public string TableName { get { return _tableName; } } }
[AttributeUsage(AttributeTargets.Property|AttributeTargets.Field, AllowMultiple = false, Inherited = false)] public class ColumnNameAttribute:Attribute { private string _columnName; public ColumnNameAttribute(string columnName) { _columnName = columnName; } public string ColumnName { get { return _columnName; } } }
2.在Model上使用特性
[TableName("Category")] public class Category:BaseEntity<long> { /// <summary> /// 类别名称 /// </summary> [ColumnName("Name")] public string Name { get; set; } /// <summary> /// 类别编码 /// </summary> [ColumnName("Code")] public string Code { get; set; } /// <summary> /// 父类别编码 /// </summary> public string ParentCode { get; set; } /// <summary> /// 类别链接 /// </summary> public string Url { get; set; } /// <summary> /// 类别层级 /// </summary> public int CategoryLevel { get; set; } /// <summary> /// 状态 /// </summary> public StateEnums State { get; set; } }
3.反射获取特性信息
[TestMethod] public void AttributeTest() { Type type = typeof(Category); //获取类class上的特性 var tableNameAttribute = (TableNameAttribute)type.GetCustomAttributes(typeof(TableNameAttribute), false).FirstOrDefault(); if (tableNameAttribute != null) { string tableName = tableNameAttribute.TableName; } //获取属性Property上的特性 foreach (var property in type.GetProperties()) { var columnNameAttribute = (ColumnNameAttribute)property.GetCustomAttributes(typeof(ColumnNameAttribute), false).FirstOrDefault(); if(columnNameAttribute != null) { string columnName = columnNameAttribute.ColumnName; } } }