自定义属性和枚举器

发布于 2024-09-29 06:32:38 字数 380 浏览 3 评论 0原文

我有一个枚举:

public enum Navigation
{
    Top = 0,
    Left = 2,
    Footer = 3
}

并且我有一个控制器操作:

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

我希望能够按如下方式装饰我的操作:

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

任何想法如何实现这一点,我可能必须创建一个自定义属性,但是我如何合并这个枚举进入它?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

も星光 2024-10-06 06:32:38

一种方法:

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

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

如果您确实想使用枚举,恐怕您将无法将它们用作属性。但是您可以将它作为参数传递给属性。像这样的事情:

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

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

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(){}
零度℉ 2024-10-06 06:32:38

属性注释只能使用从 System.Attribute 类派生的类来创建。

因此,不可能直接使用enum

但是,可以将枚举值传递给自定义属性的构造函数。像这样:

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();
}

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文