¿Cómo obtengo los atributos personalizados de un método desde Action<T>
?¿Cómo obtengo los atributos personalizados de un método de Acción <T>?
Ejemplo:
//simple custom attribute
public class StatusAttribute : Attribute
{
public StatusAttribute()
{
Message = "";
}
public string Message { get; set; }
}
// 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?
}
que darse cuenta de que podía hacer esto mediante el uso de la reflexión sobre Foo, pero por lo que estoy tratando de crear tengo que utilizar un Action<T>
.
prefiero ir a la ruta de la sintaxis más limpia, pero ese es un método de extensión impresionante. – mbursill