你如何读取一个属性的值的方法 [英] How do you Read the value of an attribute in a Method

查看:179
本文介绍了你如何读取一个属性的值的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够从我的方法看我的属性值,我该怎么办呢?

  [MyAttribute(的Hello World)
公众诠释的MyMethod()
{
    //需要阅读MyAttribute属性并获得其值
}
 

解决方案

您需要调用 GetCustomAttributes 一个 MethodBase 对象上的功能。
获得最简单的方式 MethodBase 对象是调用<一个href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx"><$c$c>MethodBase.GetCurrentMethod. (请注意,您应该添加 [MethodImpl(MethodImplOptions.NoInlining)]

例如:

  MethodBase方法= MethodBase.GetCurrentMethod();
MyAttribute ATTR =(MyAttribute)method.GetCustomAttributes(typeof运算(MyAttribute),真)[0];
字符串值= attr.Value; //假设条件是MyAttribute有一个叫做财产价值
 

您还可以得到 MethodBase 手动,像这样:(这将是更快)

  MethodBase方法= typeof运算(MyClass的).GetMethod(的MyMethod);
 

I need to be able to read the value of my attribute from within my Method, how can I do it?

[MyAttribute("Hello World")]
public int MyMethod()
{
    //Need to read the MyAttribute attribute and get its value
}

解决方案

You need to call the GetCustomAttributes function on a MethodBase object.
The simplest way to get the MethodBase object is to call MethodBase.GetCurrentMethod. (Note that you should add [MethodImpl(MethodImplOptions.NoInlining)])

For example:

MethodBase method = MethodBase.GetCurrentMethod();
MyAttribute attr = (MyAttribute)method.GetCustomAttributes(typeof(MyAttribute), true)[0] ;
string value = attr.Value;    //Assumes that MyAttribute has a property called Value

You can also get the MethodBase manually, like this: (This will be faster)

MethodBase method = typeof(MyClass).GetMethod("MyMethod");

这篇关于你如何读取一个属性的值的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆