0

您好,我有一个属性类,例如:

[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 我的枚举)

    [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);
        }
    }

我从这里有属性阅读器如何在运行时读取类的属性?

 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 中的原因

感谢帮助。

4

2 回答 2

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);
}

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

于 2013-03-29T13:46:39.273 回答
1

你将不得不去MethodInfo你的类型。尝试调用GetMethods().

于 2013-03-29T13:46:39.433 回答