.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使用自定义类属性的更多相关文章

  1. 自定义类属性设置及setter、getter方法的内部实现

    属性是可以说是面向对象语言中封装的一个体现,在自定义类中设置属性就相当于定义了一个私有变量.设置器(setter方法)以及访问器(getter方法),其中无论是变量的定义,方法的声明和实现都是系统自动 ...

  2. WPF中Image控件绑定到自定义类属性

    首先我们定义一个Student类,有ID,Name,Photo(保存图片路径). using System; using System.Collections.Generic; using Syste ...

  3. 自定义类在PropertyGrid上的展示方法

    自定义类在PropertyGrid上的展示方法 零.引言 PropertyGrid用来显示某一对象的属性,但是并不是所有的属性都能编辑,基本数据类型(int, double等)和.Net一些封装的类型 ...

  4. SpriteBuilder中不能编辑自定义类或不能给节点添加属性的解决

    不能编辑自定义类 你选中一个Sub File(CCBFile)节点,在这个例子中,该节点的Custom class区域灰化禁用且不能修改.这是因为你需要在该Sub File引用的CCB文件中修改Cus ...

  5. Qt+QGIS二次开发:自定义类实现查询矢量数据的属性字段值(图查属性)

    在GIS领域,有两种重要的查询操作,图查属性和属性查图. 本文主要介绍如何在QGIS中通过从QgsMapToolIdentify中派生自定义类实现查询矢量数据的属性字段值(图查属性). 重点参考资料: ...

  6. 第六种方式,python使用cached_property缓存装饰器和自定义cached_class_property装饰器,动态添加类属性(三),selnium webdriver类无限实例化控制成单浏览器。

    使用 from lazy_object_proxy.utils import cached_property,使用这个装饰器. 由于官方的行数比较少,所以可以直接复制出来用自己的. class cac ...

  7. [Yii2.0] 以Yii 2.0风格加载自定义类或命名空间 [配置使用Yii2 autoloader]

    Yii 2.0最显著的特征之一就是引入了命名空间,因此对于自定义类的引入方式也同之前有所不同.这篇文章讨论一下如何利用Yii 2.0的自动加载机制,向系统中引入自定义类和命名空间.本文旨在抛砖引玉,如 ...

  8. JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式

    相关链接: JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式 JS面向对象(2) -- this的使用,对 ...

  9. Android之探究viewGroup自定义子属性参数的获取流程

    通常会疑惑,当使用不同的布局方式时,子view得布局属性就不太一样,比如当父布局是LinearLayout时,子view就能有效的使用它的一些布局属性如layout_weight.weightSum. ...

随机推荐

  1. C++ 实现的一个打印日历程序

    C++ 实现的一个打印日历程序 说明:总共有三个文件 1.month.h 为定义函数的头文件 2.month.cpp 为函数的实现代码 3.mainprog.cpp 为主函数的实现代码 month.h ...

  2. checkbox 更改样式

    html: <div class="wrap"> <p>1. 勾选</p> <input type="checkbox" ...

  3. (15) go 方法

  4. linux——(5)文件与文件系统的压缩与打包

    概念一:常见的压缩文件拓展名 .z compress程序压缩的文件. .gz gzip程序压缩的文件. .bz2 bzip2程序压缩的文件. .tar tar程序打包的数据,并没有压缩过. .tar. ...

  5. Unity 游戏开发技巧集锦之制作一个望远镜与查看器摄像机

    Unity 游戏开发技巧集锦之制作一个望远镜与查看器摄像机 Unity中制作一个望远镜 本节制作的望远镜,在鼠标左键按下时,看到的视图会变大:当不再按下的时候,会慢慢缩小成原来的视图.游戏中时常出现的 ...

  6. FastReport.Net使用:[38]关系的使用

    打印所有成绩 1. 数据源准备 接下来我们需要打印学生成绩,而成绩表中无姓名,我们通过建立Realtion关系来打印数据. 2. 创建Relation关系 在数据视图上的动作下拉菜单中选择“新建关系” ...

  7. WNDR4300v2 固件编译

    WNDR4300v2 固件编译 1.从官网下载源码   从官网找到 https://kb.netgear.com/2649/NETGEAR-Open-Source-Code-for-Programme ...

  8. CXF和Axis2的区别

    1.CXF支持 WS-Addressing,WS-Policy, WS-RM, WS-Security和WS-I Basic Profile.Axis2不支持WS-Policy,但是承诺在下面的版本支 ...

  9. Failed to read auto-increment value from storage engine错误的处理方法

    在进行数据的插入时,系统提示Failed to read auto-increment value from storage engine(从存储引擎读取自增字段失败)错误,经查阅资料,解决方法如下: ...

  10. [转]Jquery实现页面定时跳转

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...