gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:09:38 25 4
gpt4 key购买 nike

我正在为我的 .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com