C# 自定义特性

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();
            }
        }
    }
}
View Code

一些Orm的实现,就是通过解析特性信息,动态生成数据库表

posted @ 2016-12-01 23:55  天碼行空  阅读(2377)  评论(0编辑  收藏  举报