网络编程 
首页 > 网络编程 > 浏览文章

.net使用自定义类属性实例

(编辑:jimmy 日期: 2025/7/1 浏览:3 次 )

一般来说,在.net中可以使用Type.GetCustomAttributes获取类上的自定义属性,可以使用PropertyInfo.GetCustomAttributes获取属性信息上的自定义属性。
 
下面以定义一个简单数据库表的映射实体类来说明相关的使用方法,基于自定义类属性和自定义类中的属性的自定义属性,可以方便的进行类标记和类中属性的标记
 
创建一个类的自定义属性,用于标识数据库中的表名称,需要继承自Attribute类:

复制代码 代码如下:[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class TableAttribute : Attribute
{
        private readonly string _TableName = "";
        public TableAttribute(string tableName)
        {
            this._TableName = tableName;
        }
        public string TableName
        {
            get { return this._TableName; }
        }
}

创建一个属性的自定义属性,用于标识数据库表中字段的名称,需要继承自Attribute类:

复制代码 代码如下:[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class FieldAttribute : Attribute
{
        private readonly string _FieldName = "";    ///数据库的字段名称
        private System.Data.DbType _Type = System.Data.DbType.String;   ///数据库的字段类型
 
        public FieldAttribute(string fieldName)
       {
              this._FieldName=fieldName;
       }
 
        public FieldAttribute(string fieldName,System.Data.DbType type)
       {
              this._FieldName=fieldName;
              this._Type=type;
       }
 
       public string FieldName
        {
            get { return this._FieldName; }
        }
 
        public System.Data.DbType Type
        {
             get{return this._Type;}
        }
}
 
创建一个数据实体基类:

复制代码 代码如下:public class BaseEntity
{
        public BaseEntity()
        {
        }
 
         /// <summary>
        /// 获取表名称
        /// </summary>
        /// <returns></returns>
        public string GetTableName()
        {
            Type type = this.GetType();
            object[] objs = type.GetCustomAttributes(typeof(TableAttribute), true);
            if (objs.Length <= 0)
            {
                throw new Exception("实体类没有标识TableAttribute属性");
            }
            else
            {
                object obj = objs[0];
                TableAttribute ta = (TableAttribute)obj;
                return ta.TableName;                            //获取表名称
            }
        }
        /// <summary>
        /// 获取数据实体类上的FieldAttribute
        /// </summary>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public FieldAttribute GetFieldAttribute(string propertyName)
        {
            PropertyInfo field = this.GetType().GetProperty(propertyName);
            if (field == null)
            {
                throw new Exception("属性名" + propertyName + "不存在");
            }
            object[] objs = field.GetCustomAttributes(typeof(FieldAttribute), true);
            if (objs.Length <= 0)
            {
                throw new Exception("类体属性名" + propertyName + "没有标识FieldAttribute属性");
            }
            else
            {
                object obj = objs[0];
                FieldAttribute fieldAttribute=(FieldAttribute)obj;
                fieldAttribute.FieldValue=field.GetValue(this,null);
                return fieldAttribute;
            }
        }
}
 
创建数据实体:

复制代码 代码如下:[Table("Wincms_Dictionary")]            ///映射到数据库的Wincms_Dictionary表
public class Wincms_Dictionary : BaseEntity
{
         private int _DictionaryId;
 
         public Wincms_Dictionary()
         {
         }
 
        [Field("DictionaryId",DbType.Int32)]                ///映射到数据库的Wincms_Dictionary表中的字段
        public int DictionaryId
        {
            get { return this._DictionaryId; }
            set
            {
                this._DictionaryId = value;
            }
        }
}
 
///基于实体类获取实体对应的表名称和字段名称
public class Test
{
 
       public static void main(string[] args)
        {
               Wincms_Dictionary dict=new Wincms_Dictionary();
               Console.WriteLine("表名称:"+GetTableName(dict));
               Console.WriteLine("字段名称:"+GetFieldName(dict,"DictionaryId"));
               Console.Read();
        }
 
       ///获取实体表名称
       public  static string GetTableName(BaseEntity entity)
       {
                return entity.GetTableName();
       }
 
       ///获取实体字段名称
       public static string GetFieldName(BaseEntity entity,string propertyName)
       {
              FieldAttribute fieldAttribute=entity.GetFieldAttribute(propertyName);
              return fieldAttribute.FieldName;
       }
}
输出结果为:

复制代码 代码如下:表名称:Wincms_Dictionary
字段名称:DictionaryId

希望本文所述对大家的.net程序设计有所帮助。

上一篇:ASP.NET中常用输出JS脚本的类实例
下一篇:.NET实现在网页中预览Office文件的3个方法
一句话新闻
一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap