C#提高--------------获取方法返回值的自定义特性(Attribute)
.NET(C#):获取方法返回值的自定义特性(Attribute)
- 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";
}
}
}
最新文章
- 【hive】——Hive初始了解
- 开源实时日志分析ELK平台部署
- 读取全球ip获取用户地区
- Greedy:Cow Acrobats(POJ 3045)
- Xcode编译错误集锦
- visual studio 2005 编fortran程序,运行后dos窗口显示问题
- mapping 详解1(mapping type)
- nodejs学习笔记-1
- pymongo数据报表脚本
- Ceph: A Scalable, High-Performance Distributed File System译文
- python六十九课——网络编程之TCP协议
- Winform开发框架中的内容及文档管理模块功能介绍
- python 模块会导入几次?猴子补丁为什么可以实现?
- day 0314函数的进阶
- storm报错:Exception in thread ";main"; java.lang.RuntimeException: InvalidTopologyException(msg:Component: [mybolt] subscribes from non-existent stream: [default] of component [kafka_spout])
- Iphone控件大全
- [NN] 随机VS批训练
- 2017-2018-1 20155216 《信息安全系统设计基础》 实现mypwd
- maven nexus linux私服搭建
- 2.PostgreSQL安装详细步骤(windows)【转】
热门文章
- 调试web api的工具 谷歌插件 Restlet
- 每日英语:America The Vulgar
- MyBean 框架入门手册<;感谢[青铜]整理的如此细致和系统>;
- Python基本语法_强制数据类型转换
- API:详解 pandas.read_csv
- 经常遇到的http状态码
- Ehcache BlockingCache 源码分析
- Ext.dom.Element 常用方法解析
- mysql 慢查询时间
- Error:不能将";char*";类型的值分配到";LPSTR";类型的实体 也许 ";char*";类型的实参与";LPCWSTR";类型的形参不兼容