使用System.Attribute作为路径属性反射

时间:2017-07-05 22:44:35

标签: c# asp.net-mvc reflection

我有属性列表,但我想获得每个属性的特定属性。例如,我有像

这样的行动
[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;
}

1 个答案:

答案 0 :(得分: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的类型一起使用,以便在using块的末尾处理它们。