你如何读取一个属性的值的方法属性、方法

2023-09-02 01:33:03 作者:今天有一点心动

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

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

解决方案

您需要调用 GetCustomAttributes 一个 MethodBase 对象上的功能。 获得最简单的方式 MethodBase 对象是调用MethodBase.GetCurrentMethod. (请注意,您应该添加 [MethodImpl(MethodImplOptions.NoInlining)]

面试问题 ibatis总 看准网

例如:

  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");

 
精彩推荐
图片推荐