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

一般来说,在.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程序设计有所帮助。

时间: 2024-08-04 08:39:36

.net使用自定义类属性实例_实用技巧的相关文章

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

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

ASP.NET中常用输出JS脚本的类实例_实用技巧

本文实例讲述了ASP.NET中常用输出JS脚本的类,针对过去输出js脚本的类进行了一定的改进.在项目开发中非常具有实用价值.分享给大家供大家参考.具体如下: 很多时候在ASP.NET中我们经常需要输出一些JS脚本,比如弹出一个警告窗口,返回到历史页面等JS功能,我看到网上流传得比较广的是马先光写的一个JScript类,这个类基本将经常用到的JS脚本包含了,非常方便,唯一的不足是作者采用的Response.Write(string msg)的办法,这样造成输出的js脚本在<html></h

Asp.Net类型转换类(通用类)代码分享_实用技巧

废话不多说了,直接给大家贴代码了,具体代码如下所述: /// <summary> /// 类型转换类 /// 处理数据库获取字段为空的情况 /// </summary> public static class DBConvert { #region------------------ToInt32类型转换------------------ /// <summary> /// 读取数据库中字符串并转换成Int32 /// 为空时返回0 /// </summary&

Asp.net内置对象之Cookies(简介/属性方法/基本操作及实例)_实用技巧

一.了解Cookies对象 Cookies是由Web服务器管理的存放在客户计算机中的一个数据集合.这些数据是客户端.服务器端相关的.也就是说客户浏览器每登录一个网站,在Cookies中就会保存客户浏览器与该网站的相关信息.即使客户用同一个浏览器登陆了多个网站,在Cookies中依然会保存浏览器与多个网站的相关信息,但Cookies中这些信息的管理是有序的,当客户浏览器再次登录某网站时,只有Cookies中相对应的信息会发生作用. Cookies是Web应用程序设计的一项很重要的技术,当Web服务

Asp.Net的FileUpload类实现上传文件实例_实用技巧

本文实例讲述了Asp.Net的FileUpload类实现上传文件的方法.分享给大家供大家参考. 具体功能代码如下: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; using System.Web.UI; using System.Web; using System.Web.UI.WebControls; using System.Collections; using System.Dra

GridView分页的实现以及自定义分页样式功能实例_实用技巧

GridView分页的实现 复制代码 代码如下: 要在GridView中加入 //实现分页 AllowPaging="true" //一页数据10行 PageSize="10" // 分页时触发的事件 OnPageIndexChanging="gvwDesignationName_PageIndexChanging" 在服务器事件里 复制代码 代码如下: protectedvoid gvwDesignationName_PageIndexChan

asp.net文件上传功能(单文件,多文件,自定义生成缩略图,水印)_实用技巧

前言 上传功能,是大家经常用到了,可能每一个项目都可以会用到.网上到处都有上传功能的代码.比我写的好的有很多.我这里也仅是分享我的代码. 功能实现点 1.单个文件上传: 2.多个文件上传: 3.对于图片等类型的图像,可以自定义生成缩略图大小: 4.文件服务器扩展. 模式 主要使用的是"模板方法"的设计模式. 本文章的功能优缺点 1.可以自定义生成缩略图的大小,任意定义.对于像微生活运动户外商城(http://sports.8t8x.com/) .淘宝网等的网站,他们需要上传大量的商品图

asp.net微信开发(自定义会话管理)_实用技巧

和微信用户的沟通少不了,总觉得看起来微信官网后台管理中的会话回复消息有点呆板,所以我这里就自定义了一个会话管理功能,最终效果图如下: 因为我试使用富文本文件CKEDITOR来进行编写,你看到稳中可能会有<P></p>字段,后台获取数据内容时,替换为空字符即可:如下 string txtcontent = this.txtMessage.Value.ToString().Replace("<p>", ""); StringBuild

ASP.NET实现基于Forms认证的WebService应用实例_实用技巧

本文实例讲述了ASP.NET实现基于Forms认证的WebService应用方法.分享给大家供大家参考.具体实现方法如下: 在安全性要求不是很高的ASP.Net程序中,基于Forms的身份验证是经常使用的一种方式,而如果需要对WebService进行身份验证,最常用的可能是基于Soap 标头的自定义身份验证方式.如果对两者做一下比较的话,显然,基于Forms的验证方式更加方便易用,能否将Forms验证方式应用到WebService中去呢? 从理论上讲,使用基于Forms的方式对WebServic