Warm tip: This article is reproduced from serverfault.com, please click

Using enum in data annotation

发布于 2020-11-28 03:30:43

I am using a data annotation like so:

[RequiresAnyRole("Admin", "Member")]

I don't like passing strings as it can be a pain refactoring later but If I try to make an enum like so:

public enum Roles
{
    Admin,
    Member
}

And then try to cast the enum to string like so:

[RequiresAnyRole(Roles.Admin.ToString(), Roles.Member.ToString())]

Then I get the error:

Error CS0182 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

My understanding of this error is that it has to be a string at compile time. I have tried to make a static dictionary with the enum as the key but that didn't work either.

What is the best way to pass these values in a way that can be refactored later i.e. not passing in a string but passing in a reference of some sort that can be updated?

Questioner
Guerrilla
Viewed
0
Sweeper 2020-11-28 11:34:54

This is a great opportunity to use nameof. You can keep your enum, and do:

[RequiresAnyRole(nameof(Roles.Admin), nameof(Roles.Member))]

nameof expressions are constant expressions.

Of course, if you can change the attribute's declaration, you should change it to accept your Roles enum.