2017-07-05 6 views
-3

属性リストがありますが、各属性の特定のプロパティを取得したいとします。 examleのために、私はSystem.Attributeをルート属性リフレクションとして使用する

[HttpGet, Route("/autocomplete")] 
[ActionInfo(Description = "bla bla bla blac")] 
// GET: AutoComplete 
public ActionResult AutoComplete() 
{ 
    return View(); 
} 


private static IEnumerable<Attribute> MyMethod(IEnumerable<Attribute> attributes) 
{ 
    foreach (Attribute attribute in attributes) 
    { 
     switch (attribute.GetType().Name) 
     { 
      case "HttpGetAttribute": 
      { 
       using (attribute as HttpGetAttribute) 
       { 
        // my business 
       } 
       break; 
      } 
      case "RouteAttribute": 
      { 
       using (attribute as RouteAttribute) 
       { 
        // my business 
       } 
       break; 
      } 
      case "ActionInfoAttribute": 
      { 
       using (attribute as ActionInfoAttribute) 
       { 
        // my business 
       } 
       break; 
      } 
     } 
    } 

    return null; 
} 

答えて

2

様作用を持っている私は、これはあなたが何をしようとしてあると思う:

private static IEnumerable<Attribute> MyMethod(IEnumerable<Attribute> attributes) 
{ 
    foreach (Attribute attribute in attributes) 
    { 
     if (attribute is HttpGetAttribute) 
     { 
      // cast to HttpGetAttribute to get properties 
     } 
     else if (attribute is RouteAttribute) 
     { 
      // cast to RouteAttribute to get properties 
     } 
     else if (attribute is ActionInfoAttribute) 
     { 
      // cast to ActionInfoAttribute to get properties 
     } 
    } 

    return null; 
} 

usingキーワードは、この文脈では意味がありません。 usingは、ブロックの最後にそれらを廃棄するためにIDisposableを実装するタイプで使用されます。

+0

C#7の 'if(属性はHttpGetAttributeがキャストされている) –

関連する問題