Bir yöntemin özel özniteliklerini Action<T>
'dan nasıl edinebilirim?Bir yöntemin özel niteliklerini Action <T>'dan nasıl edinebilirim?
Örnek:
//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?
}
ben Foo üzerinde yansıma kullanarak bu yapabilirdi farkındayım ama oluşturmaya çalışıyorum ne için ben bir Action<T>
kullanmak zorunda.
ama Bu etkileyici bir uzantısı yöntemidir. – mbursill