Id字段上的DbKey就是自定義特性
/// <summary> /// 用戶信息 /// </summary> public class User { [DbKey] public string Id { get; set; } public string Name { get; set; } }
繼承Attribute,實現自定義特性DbKey
namespace CustomerAttribute { /// <summary> /// 數據庫主鍵 /// </summary> public class DbKey : Attribute { public string Description { get; set; } public DbKey() { } public DbKey(string description) { this.Description = description; } } }
namespace CustomerAttribute { /// <summary> /// 用戶信息 /// </summary> public class User { [DbKey] public string Id { get; set; } public string Name { get; set; } } /// <summary> /// 用戶角色 /// </summary> public class UserRole { [DbKey("用戶ID")] public string UserId { get; set; } [DbKey("角色ID")] public string RoleId { get; set; } } }

namespace CustomerAttribute { class Program { /// <summary> /// 獲取數據庫主鍵字段 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> private static IEnumerable<PropertyInfo> getDbKeyFields<T>() { // 獲取當前類中的公共字段 var fields = typeof(T).GetProperties(); // 查找有DbKey特性的字段 var keyFields = fields.Where(field => (DbKey)Attribute.GetCustomAttribute(field, typeof(DbKey)) != null); return keyFields; } private static string getDescription(PropertyInfo field) { string result = string.Empty; var dbKey = (DbKey)Attribute.GetCustomAttribute(field, typeof(DbKey)); if (dbKey != null) result = dbKey.Description; return result; } static void Main(string[] args) { try { var userKeyFields = getDbKeyFields<User>(); Console.WriteLine("User表的主鍵為:" + string.Join(",", userKeyFields.Select(field => field.Name))); var userRoleKeyFields = getDbKeyFields<UserRole>(); Console.WriteLine("UserRole表的主鍵為:" + string.Join(",", userRoleKeyFields.Select(field => field.Name))); foreach (PropertyInfo field in userRoleKeyFields) { string description = getDescription(field); Console.WriteLine(string.Format("{0}字段的描述信息為:{1}", field.Name, description)); } } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.ReadLine(); } } } }
一些Orm的實現,就是通過解析特性信息,動態生成數據庫表