开发者

Custom Attributes and enumerators

I have an enum:

public开发者_运维百科 enum Navigation
{
    Top = 0,
    Left = 2,
    Footer = 3
}

And i have a controller action:

public ActionResult Quotes()
{
    return View();
}

I would like to be able to decorate my action as follow:

[Navigation.Top]
public ActionResult Quotes()
{
    return View();
}

Any idea how this could be accomplished, i will probably have to create a custom attribute, but how do i incorporate this enum into it?


One approach:

public static class Navigation{
  public class Top:ActionFilter /*any attribute*/{
   //magic
  }
  public class Left:ActionFilter{
   //magic
  }
}

[Navigation.Top]
public ActionResult Whatever(){}

If You do want to use enums, I'm afraid You won't be able to use them as attributes. But You can pass it to attribute as an argument. Something like this:

public class NavigationAttribute:Attribute{
  public Navigation Place {get;set;}
}

[Navigation(Place=Navigation.Top)]
public ActionResult Whatever(){}


Attribute annotations can only be created with classes derived from System.Attribute class.

So, it is not possible to use enum directly.

However it is possible to pass your enum value to the constructor of custom attribute. Like this:

enum Navigation 
{
    Top = 0,
    Left = 2,
    Footer = 3,
}
class NavigationAttribute: Attribute
{
    Navigation _nav;
    public NavigationAttribute(Navigation navigation){
        _nav = navigation;
    }
}
...
[Navigation(Navigation.Top)]
public ActionResult Quotes()
{
    return View();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜