• 了解attribute

Attribute 只是将一些附加信息与某个目标元素关联起来的方式。

Attribute 是一个类,这个类可以提供一些字段和属性,不应提供公共方法,事件等。在定义attribute类的构造方法,字段和属性时,对数据类型有严格的要求,一般要求为: Boolean, Char, Byte, Sbyte, Int16, UInt16, Int32, Int64,Single, Double, String, Type, Object, Enum, 可以使用数组,但是并不提倡使用。

  • 使用attribute

 [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false)]
[Conditional("Specify")]
public class DisplayNameAttribute : Attribute
{
public string PropertyName { get; set; } public DisplayNameAttribute()
{ } public DisplayNameAttribute(string propertyName)
{
this.PropertyName = propertyName;
}
}
  • 检测attribute
  1. attribute定义和应用之后还没有任何意义,只有在运行的时候去检测,然后根据对应的attribute做一些不同事情才让attribute变得有意义,那么如何检测attribute呢?

方法名称

说明

IsDefined

如果至少有一个指定的Attribute派生类的实例与目标关联,就返回true。这个方法效率很高,因为他不构造(反序列化)attribute类的任何实例

GetCustomAttributes

返回一个数组,其中每个元素都是应用于目标的指定attribute类的一个实例。

如果不为这个方法指定具体的attribute类,数组中包含的就是已应用的所有attribute的实例,不管他们是什么类。每个实例都使用编译时指定的参数、字段和属性来构造(反序列化)。如果目标没有应用任何attribute类的实例,就返回一个空数组。该方法通常用于已将AllowMultiple 设为true的attribute

GetCustomAttribute

返回应用于目标的指定attribute类的一个实例。实例使用编译是指定的参数、字段和属性来构造(反序列化)。如果目标没有应用任何attribute类的实例,就返回null。如果目标应用了制定attribute的多个实例,抛出异常AmbiguousMatchException. 因此该方法通常用于AllowMultiple=false的attribute

     最后的例子中展示了如何使用这些方法。

2.   上面的方法在检测时进行了attribute对象的构造(需要反序列化),这样有可能调用set访问器和构造方法,可能出现安全风险(未知代码在AppDomain中运行)。因此可以使用CustomAttributeData类中定的静态方法进行检测

 public override string ToString()
{
//在子类中对父类中的方法进行重写,使用不创建attribute对象不执行代码(反序列化)的方法
StringBuilder value = new StringBuilder();
if (!this.GetType().IsClass)
return value.ToString();
PropertyInfo[] properties = this.GetType().GetProperties(); foreach (var property in properties)
{
string propertyName = property.Name;
IList<CustomAttributeData> list = CustomAttributeData.GetCustomAttributes(property);
foreach (var item in list)
{
if (item.Constructor.DeclaringType == typeof(DisplayNameAttribute))
{
Console.Write("This property applies DisplayNameAttribute.");
}
}
}
return base.ToString();
}
  • 条件attribute

应用attribute时生成元数据,如果想让attribute在编译是不生成元数据可以使用条件编译,下面是例子

 #define Specify
//#define UnSpecify namespace Attribute
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics; public class Pepople
{
[DisplayName("姓名")]
[TestDemoAttribute]
public string Name { get; set; }
} public class Man : Pepople
{
[DisplayName("年龄")]
public int Age { get; set; } public float Height { get; set; }
} [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false)]
[Conditional("Specify")]
public class DisplayNameAttribute : Attribute
{
public string PropertyName { get; set; } public DisplayNameAttribute()
{ } public DisplayNameAttribute(string propertyName)
{
this.PropertyName = propertyName;
}
} [Conditional("UnSpecify")]
public class TestDemoAttribute : Attribute
{ }
}
条件attribute

 注意:赘述一句,在C#中进行预定义时,必须在文件在最前面

我们用ildasm查看元数据得知,TestDemoAttribute 没有被编译成员数据,而DisplayNameAttribute被编译成了元数据

  • 实例

对上面提到的知识写了个例子,以便加强知识的理解运用。

 #define Specify
//#define UnSpecify namespace Attribute
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics; public class Pepople
{
[DisplayName("姓名")]
[TestDemoAttribute]
public string Name { get; set; } public override string ToString()
{
StringBuilder value = new StringBuilder();
if (!this.GetType().IsClass)
return value.ToString();
PropertyInfo[] properties = this.GetType().GetProperties(); foreach (var property in properties)
{
string propertyName = property.Name;
if (property.IsDefined(typeof(DisplayNameAttribute), false))
{
DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(property, typeof(DisplayNameAttribute));
if (attr != null)
{
propertyName = attr.PropertyName;
}
}
value.Append(propertyName);
value.Append("\t");
value.Append(property.GetValue(this, null));
value.Append("\n\r");
} return value.ToString();
}
} public class Man : Pepople
{
[DisplayName("年龄")]
public int Age { get; set; } public float Height { get; set; }
} public static class OutputerClass
{
public static string StringClass(object obj)
{
StringBuilder value = new StringBuilder();
if (!obj.GetType().IsClass)
return value.ToString();
PropertyInfo[] properties = obj.GetType().GetProperties(); foreach (var property in properties)
{
DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(property, typeof(DisplayNameAttribute));
if (attr != null)
{
value.Append(attr.PropertyName);
value.Append("\t");
value.Append(property.GetValue(obj, null));
value.Append("\n\r");
}
} return value.ToString();
}
} //可以用attributeUsage声明属性应用的范围,可以多选,多选的时候|运算即可
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, Inherited = false)]
[Conditional("Specify")]
public class DisplayNameAttribute : Attribute
{
public string PropertyName { get; set; } public DisplayNameAttribute()
{ } public DisplayNameAttribute(string propertyName)
{
this.PropertyName = propertyName;
}
} [Conditional("UnSpecify")]
public class TestDemoAttribute : Attribute
{ }
}

实例

再次深入 C# Attribute的更多相关文章

  1. C#基础---Attribute(标签) 和 reflect(反射) 应用二

    以前我有写过一篇有关,打标签和反射的应用,主要用于类中字段的验证.下面是连接 C#基础---Attribute(标签) 和 reflect(反射) 应用. 这个项目迭代发现公司项目里面发现老代码对业务 ...

  2. 有关attribute和property,以及各自对select中option的影响

    这个问题老生常谈,但是直到现在我依旧时常会把它搞混.下面列一些各自的特性.   attribute property 设置方法 option.setAttribute('selected', true ...

  3. OAF_开发系列06_实现OAF属性集的介绍和开发Attribute Set(案例)

    20150705 Created By BaoXinjian

  4. 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【外传】——Attribute Routing

    系列导航地址http://www.cnblogs.com/fzrain/p/3490137.html 题外话:由于这个技术点是新学的,并不属于原系列,但借助了原系列的项目背景,故命名外传系列,以后也可 ...

  5. .net学习之Attribute特性和EF关键知识点

    一.Attribute特性/标签1.Attribute用来对类.属性.方法等标注额外的信息,贴一个标签简单的说,定制特性Attribute,本质上就是一个类,它为目标元素提供关联附加信息,并在运行时以 ...

  6. Attribute "lazy" with value "true" must have a value from the list "false proxy no-proxy "

    Hibernate 3.2 版本 当设置lazy="true"属性时,会产生该个异常: Attribute "lazy" with value "tr ...

  7. 深入浅出Attribute (转载)

    原文地址:http://blog.csdn.net/FantasiaX/article/details/1627694 正文: 什么是Attribute?Attribute是干什么使的?Attribu ...

  8. Flash Attribute

    参考:http://www.open-open.com/lib/view/open1397266120028.html 为解决POST/Forward/GET出现的重复提交数据问题,改用POST/Re ...

  9. C#中的Attribute和Java中的Annotation

    在之前的博客中介绍过C#的Attribute(特性),简单的说,特性主要就是利用反射技术,在运行期获取关注类的相关标注信息,然后利用这些标注信息对关注的类进行处理,最近因为工作的原因,需要看一下Jav ...

随机推荐

  1. 基于 Consul 的 Docker Swarm 服务发现

    Docker 是一种新型的虚拟化技术,它的目标在于实现轻量级操作系统的虚拟化.相比传统的虚拟化方案,Docker 虚拟化技术有一些很明显的优势:启动容器的速度明显快于传统虚拟化技术,同时创建一台虚拟机 ...

  2. 【Java】ArrayList 的 toArray() 方法抛出 ClassCastException 异常

    第一次用这个方法,结果冒出个莫名其妙的异常来: String[] names = (String[]) mTags.toArray(); 结果会抛出 java.lang.ClassCastExcept ...

  3. openstack私有云布署实践【10.1 计算nova - kxcontroller节点配置(科兴环境)】

    一.首先登录kxcontroller1创建kx_nova数据库,并赋于远程和本地访问的权限.     mysql -u root -p   CREATE DATABASE kx_nova; GRANT ...

  4. python中判断语句用两个or连接的奇葩

    学python的时候犯的一个错误,放在这吧.就是在循环某个列表的时候不要去操作它,这是容易忽略的一个地方.所以如果要操作某个列表本身,那么先把该列表copy一份,然后再读取的时候读copy的那份.操作 ...

  5. Unity人工智能学习—确定性AI算法之追踪算法二

    转自:http://blog.csdn.net/zhangxiao13627093203/article/details/47658673 上一篇讲到了追踪算法的比较简单的形式,看上去比较假,因为AI ...

  6. 通过一个表的id同时查询多个表的数据

    'select c.字段名,x.字段名 as 改为新的显示名,x.字段名 from 表名1 b,表名2 c,表名3 x where b.字段id=' . $id . ' and b.`字段id`=c. ...

  7. Excel的 OleDb 连接串的格式(Provider=Microsoft.ACE.OLEDB)

    string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;data source=" + filePath + ";Exten ...

  8. Openjudge-NOI题库-Pell数列

    题目描述 Description Pell数列a1, a2, a3, ...的定义是这样的,a1 = 1, a2 = 2, ... , an = 2 * an − 1 + an - 2 (n > ...

  9. HTML5历史管理

    边看视频边做的练习,随机显示数字,分别使用history和hash来实现历史管理 <!doctype html> <html> <head> <meta ch ...

  10. 【实验室笔记】C#的Socket客户端接收和发送数据

    采用socket发送和接收数据的实验中,服务器采用的是网络助手作为模拟服务器端. 客户端程序流程: 应用的命名空间: using System.Net; using System.Net.Socket ...