【问题标题】:Use enum item name like an attribute parameter像属性参数一样使用枚举项名称
【发布时间】:2012-08-24 08:05:56
【问题描述】:

我只是不想为每个属性使用“经理”,而是为此使用一些枚举。

但似乎不可能还是我错了?

所以我尝试替换

[RequiresRole("Managers")]

[RequiresRole(HardCodedRoles.Managers.ToString())]

...

public enum HardCodedRoles
{ 
            Administrators,
            Managers
}

【问题讨论】:

  • 您能否添加更多细节,以便我们知道您要完成的工作是什么?
  • 我只是不想使用字符串“AnyRoleName”,我想从枚举中放置一些项目而不是它。但是VS报错An attribute argument must be an constant expression, typeof expression or array creation expression of an attribute parameter type
  • 如果 HardcodedRoles.Managers 是一个 const 字符串,这将起作用。另一方面,如果 HardcodedRoles 是一个枚举,则必须继承 AuthorizeAttribute 并实现自己的,将 HardcodedRoles 和/或 HardcodedRoles[] 传递给构造函数。
  • @Maciej 你能提供任何样品吗?我刚刚找到了一些链接stackoverflow.com/questions/2397923/…,这里是stackoverflow.com/questions/1315524/…,这里是geekswithblogs.net/thomasthedeuce/archive/2009/06/25/…,但无法弄清楚它是如何完成的。

标签: c# .net wcf-ria-services


【解决方案1】:

用一个类而不是一个枚举怎么样,使这个类成为静态的以避免有人新的:ing 它?

public static class HardCodedRoles
{
    public const string Managers = "Managers";
    public const string Administrators = "Administrators";
}

[RequiresRole(HardCodedRoles.Managers)] 

【讨论】:

  • 这并不限制某人使用[RequiresRole("fred")]。够了吗?
  • 不使用枚举作为问题状态。问题需要更改,或者应该标记另一个答案。
【解决方案2】:

您也可以使用 nameof 关键字,即:

[RequiresRole(nameof(HardCodedRoles.Managers))]

【讨论】:

  • 为什么这不是公认的答案?问题是如何使用枚举作为属性,这是正确的。接受的答案甚至不使用枚举。
【解决方案3】:

您看到错误的原因是因为ToString() 是一个方法,因此无法在编译时计算该值。

如果您可以改用 [RequiresRole(HardCodedRoles.Managers)],您可以在代码的其他地方执行 ToString,这可以为您提供所需的功能。这将要求您将属性的参数从 string 更改为 HardCodedRoles

(我想使用const 是行不通的,因为参数的类型仍然是string,所以输入不会受到限制。)

【讨论】:

  • 谢谢!您能否提供任何示例“如果您可以使用 [RequiresRole(HardCodedRoles.Managers)],您可以在代码的其他地方执行 ToString,这可以为您提供所需的功能。”
  • 您需要什么样品?
猜你喜欢
  • 1970-01-01
  • 2016-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多