簡體   English   中英

如何使用反射從MethodInfo獲取WebGetAttribute

[英]How to Get WebGetAttribute from MethodInfo Using Reflection

當我運行此代碼時attrs值為空

IEnumerable<object> attrs = ((typeof(Data).GetMethods().Select
(a => a.GetCustomAttributes(typeof(WebGetAttribute),true))));  
WebGetAttribute wg= attrs.First() as WebGetAttribute;    // wg is null

這是我班上要反映的:

public class Data
    {
       [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, UriTemplate = "/GetData")]
       string GetData(int value)
       {
           return "";
       }
    }

請我需要幫助以了解有關WCF服務中每個方法的此信息(方法類型/ ResponseFormat / UriTemplate)

您似乎沒有選擇NonPublic方法或正確的屬性類型。

您可以嘗試:

IEnumerable<object> attrs = 
     typeof(Data).GetMethods(BindingFlags.Public|BindingFlags.NonPublic)
      .SelectMany(a => a.GetCustomAttributes(typeof(WebInvokeAttribute),true));  

WebInvokeAttribute wi = attrs.First() as WebInvokeAttribute ;    

jbl是正確的。 沒有BindingFlags參數,GetMethods將不會返回非公共方法。 另外,由於WebInvokeAttribute不繼承WebGetAttribute,因此GetCustomAttributes不會返回它。

以下代碼將為所有公共和非公共方法選擇WebInvokeAttributes:

IEnumerable<object> attrs = typeof(Data)
    .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
    .SelectMany(a => a.GetCustomAttributes(typeof(WebInvokeAttribute), true));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM