如何从 Action<T> 获取方法的自定义属性? [英] How do I get the custom attributes of a method from Action&lt;T&gt;?

查看:37
本文介绍了如何从 Action<T> 获取方法的自定义属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Action 委托获取方法的自定义属性?

How can I get the custom attributes of a method from a Action<T> delegate?

示例:

//simple custom attribute
public class StatusAttribute : Attribute
{

    public string Message { get; set; } = string.Empty;
}

// an extension methodto wrap MethodInfo.GetCustomAttributes(Type, Bool) with
// generics for the custom Attribute type
public static class MethodInfoExtentions
{
    public static IEnumerable<TAttribute> GetCustomAttributes<TAttribute>(this MethodInfo methodInfo, bool inherit) where TAttribute : Attribute
    {
        object[] attributeObjects = methodInfo.GetCustomAttributes(typeof(TAttribute), inherit);
        return attributeObjects.Cast<TAttribute>();
    }
}

// test class with a test method to implment the custom attribute
public class Foo
{
    [Status(Message="I'm doing something")]
    public void DoSomething()
    {
        // code would go here       
    }
}

// creates an action and attempts to get the attribute on the action
private void CallDoSomething()
{
    Action<Foo> myAction = new Action<Foo>(m => m.DoSomething());
    IEnumerable<StatusAttribute> statusAttributes = myAction.Method.GetCustomAttributes<StatusAttribute>(true);

    // Status Attributes count = 0? Why?
}

我意识到我可以通过在 Foo 上使用反射来做到这一点,但是对于我要创建的内容,我必须使用 Action.

I realize I could do this by using reflection on Foo, but for what I'm trying to create I have to use an Action<T>.

推荐答案

问题是动作没有直接指向 Foo.DoSomething.它指向以下形式的编译器生成的方法:

The problem is that the action doesn't directly point at Foo.DoSomething. It points at a compiler-generated method of the form:

private static void <>__a(Foo m)
{
    m.DoSomething();
}

这里的一个选择是将其更改为 Expression>,然后您可以在之后剖析表达式树并提取属性:

One option here would be to change it to an Expression<Action<T>>, then you can dissect the expression tree afterwards and extract the attributes:

Expression<Action<Foo>> myAction = m => m.DoSomething();
var method = ((MethodCallExpression)myAction.Body).Method;
var statusAttributes = method.GetCustomAttributes<StatusAttribute>(true);
int count = statusAttributes.Count(); // = 1

这篇关于如何从 Action<T> 获取方法的自定义属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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