こんにちは、次のような属性クラスがあります。
[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);
}
}
ここから属性リーダーがあります 実行時にクラスの属性を読み取るにはどうすればよいですか?
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 の理由
手伝ってくれてありがとう。