.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. 【数学】At Coder 091 D题

    [深夜题解] 题目链接:https://arc091.contest.atcoder.jp/tasks/arc091_b 题目大意:给出两个正整数N.K,找出所有的不大于N的正整数对(a,b)使b%a ...

  2. shell 文件传 参数

    n cross-platform, lowest-common-denominator sh you use: #!/bin/sh value=`cat config.txt` echo " ...

  3. aiohttp

    发起请求 async def fetch(): async with aiohttp.ClientSession() as session: async with session.get('https ...

  4. 【BZOJ 2024】 2024: [SHOI2009] 舞会 (容斥原理+高精度)

    2024: [SHOI2009] 舞会 Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 368  Solved: 102 Description OIto ...

  5. 【BZOJ 4332】 4332: JSOI2012 分零食 (FFT+快速幂)

    4332: JSOI2012 分零食 Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 119  Solved: 66 Description 这里是欢乐 ...

  6. Tomcat+Apache集群方案

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha # environment slash for Windows(反斜杠代表Windows ...

  7. 51nod1380 夹克老爷的逢三抽一

    问题等价于选出$n / 3$个不相邻元素是权值和最大 这是一个经典贪心问题,同种树,拿堆维护即可,复杂度$O(n \log n)$ #include <queue> #include &l ...

  8. JZYZOJ1540 BZOJ4035 [ haoi2015 上午] T3 博弈论 sg函数 分块 haoi

    http://172.20.6.3/Problem_Show.asp?id=1540 之前莫比乌斯反演也写了一道这种找规律分块计算的题,没觉得这么恶心啊. 具体解释看代码. 翻硬币的具体方法就是分别算 ...

  9. java开发_mysql中获取数据库表描述_源码下载

    功能描述: 在mysql数据库中,有两张表: data_element_config , test_table 我们需要获取表:test_table表的描述信息,然后把描述信息插入到表:data_el ...

  10. 2015 UESTC 数据结构专题C题 秋实大哥与快餐店 字典树

    C - 秋实大哥与快餐店 Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/contest/show/59 ...