.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. 一个完整的 JS 身份证校验代码

    一个完整的 JS 身份证校验代码 身份证号码是由 18 位数字组成的,它们分别表示: (1) 前 1.2 位数字表示: 所在省份的代码; (2) 第 3.4 位数字表示: 所在城市的代码; (3) 第 ...

  2. 用memcached实现的php锁机制

    <?php /** * 使用Memcache实现给进程加锁的类 * * Copyright (C) 2013 JeffJing * * 一些时候需要让系统的某些操作串行化,这个时候就要对这些操作 ...

  3. anaconda-anaconda无法安装pydot?

    只需先安装graphviz,再安装pydot就可以了 sudo conda install graphviz sudo conda install pydot

  4. 【leetcode】 21. Merge Two Sorted Lists

    题目描述: Merge two sorted linked lists and return it as a new list. The new list should be made by spli ...

  5. 爱奇艺全国高校算法大赛初赛B

    二分,验证. 二分一下答案,然后验证一下统计个数能否满足即可. #include <cstdio> #include <cmath> #include <cstring& ...

  6. MYSQL注入天书之前言

    写在前面的一些内容 请允许我叨叨一顿: 最初看到sqli-labs也是好几年之前了,那时候玩了前面的几个关卡,就没有继续下去了.最近因某个需求想起了sqli-labs,所以翻出来玩了下.从每一关卡的娱 ...

  7. 【Java学习】调用ByteBuffer.getInt()方法得到808464432

    调用ByteBuffer.getInt()方法遇到的奇怪错误 最近在参加阿里的中间件比赛,中间用到了RocketMQ的思想,并且主要集中在使用NIO来读写文件.其中遇到了一个很蛋疼的问题,想了半天想不 ...

  8. 【转】全面了解Mysql中的事务

    为什么要有事务? 事务广泛的运用于订单系统.银行系统等多种场景.如果有以下一个场景:A用户和B用户是银行的储户.现在A要给B转账500元.那么需要做以下几件事: 1. 检查A的账户余额>500元 ...

  9. Makefile-filter和filter-out

    filter:代表中目标串中找出符合匹配规则的. 示例: sources := foo.c bar.c baz.s ugh.h foo: $(sources) cc $(filter %.c %.s, ...

  10. bzoj1004 purfer 序列

    之前没不知道这个数列. 一个purfer序列与一棵树一一对应. 长度为n的purfer的集合: A = { s | s is a sequence and a∈[1,len(s)+2] 一个直接的结论 ...