c# - 如何从 Action<T> 获取方法的自定义属性?

标签 c# reflection

如何从 Action<T> 中获取方法的自定义属性代表?

例子:

//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<T> .

最佳答案

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

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

此处的一个选项是将其更改为 Expression<Action<T>> ,然后您可以在之后剖析表达式树并提取属性:

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

关于c# - 如何从 Action<T> 获取方法的自定义属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4822461/

相关文章:

c# - Process.Start() 中的错误——系统找不到指定的文件

c# - 您能否在运行时从外部修改 Java(更具体地说是 javaw)的内存?

c# - 分别读取文本文件中的每个单词

c# - 如何使用反射获取 Func<T> 的返回类型?

android - 将混淆器用于 Android 应用程序时,反射方法不起作用

.net - 如何根据创建的子类的类型过滤基类中的对象集合?

c# - Azure - ASP.NET MVC 连接到 mysql 数据库

c# - 有没有办法导航到接口(interface)背后方法的实际实现?

.net - 序列化性能差的可能解决方案

java - Gradle - jacoco 任务在 Spring 应用程序运行时添加合成字段,导致计算类中已声明字段数量的测试失败