.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. 2017/11/7 Leetcode 日记

    2017/11/7 Leetcode 日记 669. Trim a Binary Search Tree Given a binary search tree and the lowest and h ...

  2. Netstat -tln 命令是Linux查看端口使用情况

    Netstat -tln 命令是Linux查看端口使用情况

  3. Scrapy基础------css选择器基础

    基本语法: * 选择所有节点 #container 选择id为container的节点 .container 选择所有class包含container的节点 li a 选取所有li 下所有a节点 ul ...

  4. NOIP2017 D2T3列队

    这题我改了三天,考场上部分分暴力拿了50,考完试发现与正解很接近只是没写出来. 对于每一行和最后一列建n+1颗线段树,维护前缀和. 复杂度qlogn 假如你移动一个坐标为(x,y)的人,你要将第x行线 ...

  5. [BZOJ3926][ZJOI2015]诸神眷顾的幻想乡(后缀自动机)

    日,无数幽香的粉丝到了幽香家门前的太阳花田上来为幽香庆祝生日. 粉丝们非常热情,自发组织表演了一系列节目给幽香看.幽香当然也非常高兴啦.  这时幽香发现了一件非常有趣的事情,太阳花田有n块空地.在过去 ...

  6. HDU 2157 How many ways?? (邻接矩阵快速幂)

    http://acm.hdu.edu.cn/showproblem.php?pid=2157 题意 : 给定一个有向图,问从A点恰好走k步(允许重复经过边)到达B点的方案数mod p的值   从这道题 ...

  7. dcoker常用命令

    记录一下常用的命令 docker run -t -i  xxxx /bin/bash 运行容器的交互会话shell docker start xxxx 启动容器 docker stop xxxx 停止 ...

  8. bzoj 1018 线段树维护连通性

    本题将一道LCT的题特殊化(支持加边和删边,询问图的连通性),将图变成了2×m的网格图,然后就神奇地可以用线段树来维护. 对于每个区间[l,r],维护其四个角落之间的连通性(仅仅通过[l,r]这段的边 ...

  9. Java高级架构师(一)第42节:应用上Nginx过后的体系结构

    以后的架构思考方向: 体系结构的演变

  10. leetcode644. Maximum Average Subarray II

    leetcode644. Maximum Average Subarray II 题意: 给定由n个整数组成的数组,找到长度大于或等于k的连续子阵列,其具有最大平均值.您需要输出最大平均值. 思路: ...