您好,我有一个属性类,例如:
[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 中的原因
感谢帮助。