你好,我有一个属性类,类似于:
[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);
}
}我这里有属性读取器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的原因
谢谢你帮忙。
发布于 2013-03-29 13:46:39
您需要从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-29 13:46:39
你将不得不去你的类型的MethodInfo。试着打电话给GetMethods()。
https://stackoverflow.com/questions/15704454
复制相似问题