如何从接口AttributeUsage=AttributeTargets.Method读取属性值
本文关键字:Method 读取 属性 AttributeTargets 接口 AttributeUsage | 更新日期: 2023-09-27 18:06:42
你好,我有一个属性类,比如:
[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中的原因。方法
谢谢你的帮助。
您需要从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);
}
您也可以使用表达式,而不是将名称指定为字符串。
您必须转到您类型的MethodInfo
。尝试调用GetMethods()
。