码迷,mamicode.com
首页 > 其他好文 > 详细

特性Attibute定义和使用

时间:2017-04-05 10:56:31      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:.property   ntc   编码   int   反射   ring   log   style   target   

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;
                }              
            }
        }

 

特性Attibute定义和使用

标签:.property   ntc   编码   int   反射   ring   log   style   target   

原文地址:http://www.cnblogs.com/marshhu/p/6667697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!