Use enumeration element name as attribute parameter

I just want not to use "Managers" for each attribute and use an enumeration for this.

But does this seem impossible or am I mistaken?

So I'm trying to replace

[RequiresRole("Managers")] 

from

 [RequiresRole(HardCodedRoles.Managers.ToString())] ... public enum HardCodedRoles { Administrators, Managers } 
+6
source share
3 answers

How about a class instead of enum, creating a static class to avoid someone new: its?

 public static class HardCodedRoles { public const string Managers = "Managers"; public const string Administrators = "Administrators"; } [RequiresRole(HardCodedRoles.Managers)] 
+11
source

The reason you see the error is because ToString() is a method, and therefore the value cannot be computed at compile time.

If you can use [RequiresRole (HardCodedRoles.Managers)], you can execute ToString elsewhere in your code, and this can give you the necessary functionality. This will require changing the parameter of your attribute from string to HardCodedRoles .

(I would suggest that using const will not work, because the type of the parameter will be string , so the input will not be limited.)

+2
source

You can also use the nameof keyword, i.e.:

 [RequiresRole(nameof(HardCodedRoles.Managers))] 
+1
source

Source: https://habr.com/ru/post/924106/


All Articles