c# - 如何避免重复条件逻辑?

标签 c# .net-core delegates func code-reuse

我正在为我的 .NET Core 应用程序实现安全功能,我发现自己一遍又一遍地重复相同的条件逻辑。 有没有一种方法可以将其概括在一个地方并将其应用于我想要的分割市场? 我记得使用委托(delegate)或 Func 来处理这类事情,但我不太确定……有什么想法吗?

下面是我尝试编写一次并应用于多个地方的代码。

var currentUser = _httpContext.HttpContext.Session.GetCurrentUser<SessionContext>();
if(currentUser.Roles.Any())
{
    // ex query here. This could be any piece of code
    var q = from u in _dbContext.Users
            join d in _dbContext.Users on u.DoctorId equals d.Id into ud
            from docU in ud.DefaultIfEmpty()
            select new
            {
                User = u,
                Doctor = docU
            };

    if(!currentUser.Roles.Contains("Administrator"))
    {
        if(currentUser.Roles.Contains("Doctor"))
        {
            //do something here
           //ex.
           q = q.Where(x => (x.Doctor != null ? x.Doctor.Id == currentUserId : false));
        }
        else if (currentUser.Roles.Contains("Patient"))
        {
            //do something else here
            //ex.
            q = q.Where(x => x.User.Id == currentUserId);
        }
    }
}
else
    throw new Exception("No roles applied to logged in user");

最佳答案

这是一些用 Swift 编写的代码。 我正在使用面向函数的编程,带有字典


struct User {
    var Roles: Set<String> = ["Doctor"]
}

func channel(user: User, _ roles: [String:() -> ()]) {
    for i in roles {
        if user.Roles.contains(i.key) { i.value() }
    }
}

let currentUser = User()
channel(user: currentUser,
       [
        "Doctor": {
        // Code for doctor
        },

        "Admin": {
        // Code for admin
        },

        "Blah": {
        // Code for blah
        },

        // You can even add more
    ]
)

你可以枚举创建一个枚举
为什么是枚举?
你可以很容易地用普通的字符串打错字
对于枚举,如果你打错了,Swift 会给你一个错误。 super 有用!

enum UserRolls { case doctor, admin, patient, other(String) }
extension UserRolls: Hashable {}

struct User {
    var Roles: Set<UserRolls> = [.doctor]
}

func channel(user: User, _ roles: [UserRolls:() -> ()]) {
    for i in roles {
        if user.Roles.contains(i.key) { i.value() }
    }
}

let currentUser = User()
channel(user: currentUser,
       [
        .doctor: {
        // Code for doctor
        },

        .admin: {
        // Code for admin
        },

        .other("Blah"): {
        // Code for blah
        },

        // You can even add more
    ]
)

关于c# - 如何避免重复条件逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61487927/

相关文章:

.net - dotnet发布包含额外的文件

javascript - 使用类选择器附加事件处理程序是否会影响该类的动态添加元素?

c# - 使用 System.Drawing.Printing 获取队列状态

asp.net-core - 在没有 ASP.NET 标识的情况下使用 Cookie 中间件时自定义 IsInRole()

c# - 如何使用 Visual Studio 2015 注册 .NET Core 1.1 RTM 的自定义项模板?

iphone - 如何在1个viewController中管理2个tableview?

ios - UIPageViewController 委托(delegate)不触发横向

c# - 将HexNumber转换为字符串的字符

c# - 使用 Caliburn.Micro 设置窗口标题

c# - 在 Visual Studio 2012 解决方案中混合 Visual Studio 2010 和 2012 项目