.NET(C#):获取方法返回值的自定义特性(Attribute)

转载 2013年05月08日 10:54:42
  • 1456

来自:http://www.cnblogs.com/mgen/archive/2011/11/02/2233374.html

.NET中特性的索取就是围绕着ICustomAttributeProvider接口(System.Reflection命名空间内),而MethodInfo类的ReturnTypeCustomAttributes属性直接返回方法返回值的ICustomAttributeProvider接口对象。同时MethodBase的ReturnParameter属性返回方法返回值信息(ParameterInfo),而ParameterInfo也是继承ICustomAttributeProvider的,所以这两个属性都可以得到方法返回值的特性。注意基类MethodBase没有相应属性,由于ConstructorInfo(代表构造函数信息)没有返回值。

代码:

using System;

using System.Reflection;

namespace Mgen

{

[AttributeUsage(AttributeTargets.ReturnValue)]

class MyAttr : Attribute

{

public int Data { get; set; }

}

class Program

{

static void Main(string[] args)

{

var method = typeof(Program).GetMethod("doo");

test(method.ReturnTypeCustomAttributes);

test(method.ReturnParameter);

}

static void test(ICustomAttributeProvider customAttrProvider)

{

if (customAttrProvider.IsDefined(typeof(MyAttr), false))

{

var att = (MyAttr)customAttrProvider.GetCustomAttributes(typeof(MyAttr), false)[0];

Console.WriteLine(att.Data);

}

}

[return: MyAttr(Data = 17)]

public static string doo()

{

return "hehe";

}

}

}

最新文章

  1. 【hive】——Hive初始了解
  2. 开源实时日志分析ELK平台部署
  3. 读取全球ip获取用户地区
  4. Greedy:Cow Acrobats(POJ 3045)
  5. Xcode编译错误集锦
  6. visual studio 2005 编fortran程序,运行后dos窗口显示问题
  7. mapping 详解1(mapping type)
  8. nodejs学习笔记-1
  9. pymongo数据报表脚本
  10. Ceph: A Scalable, High-Performance Distributed File System译文
  11. python六十九课——网络编程之TCP协议
  12. Winform开发框架中的内容及文档管理模块功能介绍
  13. python 模块会导入几次?猴子补丁为什么可以实现?
  14. day 0314函数的进阶
  15. storm报错:Exception in thread "main" java.lang.RuntimeException: InvalidTopologyException(msg:Component: [mybolt] subscribes from non-existent stream: [default] of component [kafka_spout])
  16. Iphone控件大全
  17. [NN] 随机VS批训练
  18. 2017-2018-1 20155216 《信息安全系统设计基础》 实现mypwd
  19. maven nexus linux私服搭建
  20. 2.PostgreSQL安装详细步骤(windows)【转】

热门文章

  1. 调试web api的工具 谷歌插件 Restlet
  2. 每日英语:America The Vulgar
  3. MyBean 框架入门手册<感谢[青铜]整理的如此细致和系统>
  4. Python基本语法_强制数据类型转换
  5. API:详解 pandas.read_csv
  6. 经常遇到的http状态码
  7. Ehcache BlockingCache 源码分析
  8. Ext.dom.Element 常用方法解析
  9. mysql 慢查询时间
  10. Error:不能将"char*"类型的值分配到"LPSTR"类型的实体 也许 "char*"类型的实参与"LPCWSTR"类型的形参不兼容