私は自分の役割を次のように定義しています。
[Flags]
public enum Roles : byte
{
View = 1,
Edit = 2,
Admin = (View | Edit)
}
- 表示ロール、表示のみ可能
- 編集は表示と編集のみ可能
- 管理者は管理者の作業、編集、表示を行うことができます
Enum の定義に何か問題がありますか?
私は自分の役割を次のように定義しています。
[Flags]
public enum Roles : byte
{
View = 1,
Edit = 2,
Admin = (View | Edit)
}
Enum の定義に何か問題がありますか?
That looks fine, though for flags you must remember you cannot increment by ones (1, 2, 3, 4) - it must be done like: 1, 2, 4, 8.
Using your enum definition:
[Flags]
public enum Roles : byte
{
View = 1,
Edit = 2,
Admin = (View | Edit) // Good for code readability - and if the values change
}
You can see that you can detect individual flags set like this (even specifically the Admin one).
Roles role = Roles.Admin;
bool canView = ((role & Roles.View) == Roles.View);
bool canEdit = ((role & Roles.Edit) == Roles.Edit);
bool isAdmin = (role == Roles.Admin);
You can see this work: https://dotnetfiddle.net/0pm4jW
I also like this kind of definition for readability (and not having to calculate the math if I want to add one later).
[Flags]
public enum Roles : byte
{
View = 1 << 0, // 1
Edit = 1 << 1, // 2
Delete = 1 << 2, // 4
Share = 1 << 3, // 8
Admin = (View | Edit | Delete | Share)
}
admin 定義は、ロールを分離し、Admin を使用してそれらをグループ化する場合にのみ有効です。列挙型を英語に書き換えるだけです。
View is equal View and nothing more
Edit is equal Edit and nothing more
Admin is equal Admin or Edit or View
役割のフォールバック (管理者 -> 編集 -> 表示など) が必要な場合は、それを一意の役割 (管理者であっても) と見なし、順序を使用して役割の重要性を指定する必要があります。
public enum Roles // note there is no flag attribute
{
View = 1,
Edit = 2,
Admin = 3
}
役割をテストする方法は?シンプルな関数を作成するだけです:
bool isInRole(Roles currentRole, Roles expectedRole)
{
return currentRole >= expectedRole;
}
isInRole(Roles.Admin, Roles.Admin); // true
isInRole(Roles.Edit, Roles.Admin); // false
isInRole(Roles.Edit, Roles.Edit); // true
isInRole(Roles.Edit, Roles.View); // true