【问题标题】:Prepare enum list and find an enum value from List<enum>准备枚举列表并从 List<enum> 中找到一个枚举值
【发布时间】:2013-05-19 14:08:45
【问题描述】:

我决定为访问控制列表权限检查编写以下代码。

我的数据库将返回类似EmployeeDetFeature,Create,Edit的记录

我想解析 Create 并将其添加到功能 ACL 枚举列表中。

我也需要稍后找到它。

public enum ACL
{

    Create,
    Delete,
    Edit,
    Update,
    Execute
}  


public class Feature
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<ACL> ACLItems { get; set; }
}




public static class PermissionHelper
{
    public static bool CheckPermission(Role role, string featureName, ACL acl)
    {
        Feature feature = role.Features.Find(f =>f.Name == featureName);
        if (feature != null)
        {
            //Find the acl from enum and if exists return true
            return true;
        }
        return false;
    }
}

我如何通过 Enum 集合准备来完成它,并在稍后找到相同的内容以检查权限。

【问题讨论】:

    标签: c# asp.net .net enums


    【解决方案1】:

    从枚举中找到acl,如果存在则返回true

    这样的?

    bool b= Enum.GetValues(typeof(ACL)).Cast<ACL>().Any(e => e == acl);
    

    【讨论】:

    • +1 看起来不错。让我试试。我还需要看看我将如何将每个字符串(如CreateEdit)分配给我的 ACLItems in Feature :(
    • +1:甜蜜。不过,希望您可以添加代码来演示如何通过扩展方法访问它。
    【解决方案2】:

    如果您正在使用 .NET 4.0,您可以使用 Flags 属性装饰 ACL 枚举并稍微更改您的模型:

    // Added Flags attribute.
    [Flags]
    public enum ACL
    {
        None = 0,
        Create = 1,
        Delete = 2,
        Edit = 4,
        Update = 8,
        Execute = 16
    }
    
    public class Feature
    {
        public int Id { get; set; }
        public string Name { get; set; }
        // ACLItems is not List anymore.
        public ACL ACLItems { get; set; }
    }
    

    现在您可以使用Enum.TryParse,如下例所示:

    static void Main(string[] args)
    {
        ACL aclItems = ACL.Create | ACL.Edit | ACL.Execute;
    
        var aclItemsString = aclItems.ToString();
        // aclItemsString value is "Create, Edit, Execute"
    
        ACL aclItemsOut;
        if (Enum.TryParse(aclItemsString, out aclItemsOut))
        {
            var areEqual = aclItems == aclItemsOut;
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2010-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多