如何从接口AttributeUsage = AttributeTargets.Method读取属性值

时间:2013-03-29 13:40:45

标签: c# attributes

你好,我有一个属性类,如:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class ServiceMethodSettingsAttribute : Attribute
    {
        public string ServiceName { get; private set; }
        public RequestMethod Method { get; private set; }

        public ServiceMethodSettingsAttribute(string name, RequestMethod method)
        {
            ServiceName = name;
            Method = method;
        }
    }

我有界面(RequestMethod my enum)

    [ServiceUrl("/dep")]
    public interface IMyService
    {
        [ServiceMethodSettings("/search", RequestMethod.GET)]
        IQueryable<Department> Search(string value);
    }

 public class MyService : BaseService, IMyService
    {        
        public IQueryable<Department> Search(string value)
        {
            string name = typeof(IMyService).GetAttributeValue((ServiceMethodSettingsAttribute dna) => dna.ServiceName);
            var method = typeof(IMyService).GetAttributeValue((ServiceMethodSettingsAttribute dna) => dna.Method);
        }
    }

我有来自How do I read an attribute on a class at runtime?

的读者属性
 public static class AttributeExtensions
    {
        public static TValue GetAttributeValue<TAttribute, TValue>(this Type type, Func<TAttribute, TValue> valueSelector)
            where TAttribute : Attribute
        {
            var att = type.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
            if (att != null)
            {
                return valueSelector(att);
            }
            return default(TValue);
        }
    }

我无法从 ServiceMethodSettings 属性中获取值。我有什么问题 声明以及如何以正确的方式读取值?

我还有ServiceUrl属性

[AttributeUsage(AttributeTargets.Interface, AllowMultiple = true, Inherited = true)]
    public class ServiceUrlAttribute : System.Attribute
    {
        public string Url { get; private set; }

        public ServiceUrlAttribute(string url)
        {
            Url = url;
        }
    }
它工作得很好。

可能是AttributeUsage AttributeTargets.Method

中的原因

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您需要从与该方法相对应的MethodInfo中获取属性,例如

MethodInfo method = typeof(IMyService).GetMethod("Search");
ServiceMethodSettingsAttribute attr = (ServiceMethodSettingsAttribute) method.GetCustomAttributes(typeof(ServiceMethodSettingsAttribute), true).FirstOrDefault();

对方法的直接更改是为装饰方法名称添加参数:

public static TValue GetMethodAttributeValue<TAttribute, TValue>(this Type type, string methodName, Func<TAttribute, TValue> valueSelector)
    where TAttribute : Attribute
{
    MethodInfo method = type.GetMethod(methodName);
    if(method == null) return default(TValue);
    var att = method.GetCustomAttributes(typeof(TAttribute), true)
        .Cast<TAttribute>()
        .FirstOrDefault();

    if (att != null)
    {
        return valueSelector(att);
    }
    return default(TValue);
}

您也可以使用表达式而不是将名称指定为字符串。

答案 1 :(得分:1)

您必须转到您所在类型的MethodInfo。尝试拨打GetMethods()