c# - 如何缩短 C# 中的大量 IF 语句?
问题描述
我正在对数据库中的每个表进行一些数据过滤,这个数据库有 567 个表
所以这是我对 1 个表的过滤器 [来源]
if (Context.Request.UrlReferrer.ToString().ToLower().Contains("Source"))
AccessControlRule("SourceID",
"select SourceID from Source where IsDelete = 0",
AccessPermission.Allow);
else
AccessControlRule("SourceID",
"select SourceID from Source where IsDelete = 1 OR IsDelete = null",
AccessPermission.Allow);
上面的代码片段过滤了Sources。现在我正在为所有表编写 IF 语句,这意味着有很多代码 &(复制/粘贴),我担心这会导致很多人为错误。
你有办法缩短这个吗?也许是循环类型的过程?
谢谢!
解决方案
好吧,你并没有真正提供足够的信息,但我会咬一口......假设你所有的表/代码都遵循相同的模式,它相当简单:
// You'll want to whitelist the tables, so you are not
// trusting user input for the table name
var tables = new List<String>() { "Source", ... };
foreach(var table in tables){
if (Context.Request.UrlReferrer.ToString().ToLower().Contains(table)){
AccessControlRule(
$"{table}ID",
"select {table}ID from {table} where IsDelete = 0",
AccessPermission.Allow
);
} else {
AccessControlRule(
$"{table}ID",
"select {table}ID from {table} where IsDelete = 1 OR IsDelete = null",
AccessPermission.Allow
);
}
}
但是 - 您可能不想使用 Referrer 值实际配置 AccessRules 或 Security 之类的东西,因为它可能会被轻而易举地欺骗......您不依赖此代码来实现某种形式的安全性,是吗?
编辑如果您的键不同,您可以只使用 tablename -> keyname 的映射(通过 Dictionary 可能是最简单的)而不是列表:
// You'll want to whitelist the tables, so you are not
// trusting user input for the table name
var tables = new Dictionary<String, String>() {
{"Source", "SourceId" },
...
};
foreach(var table in tables){
if (Context.Request.UrlReferrer.ToString().ToLower().Contains(table.Key)){
AccessControlRule(
$"{table.Value}",
"select {table.Value} from {table.Key} where IsDelete = 0",
AccessPermission.Allow
);
} else {
AccessControlRule(
$"{table.Value}",
"select {table.Value} from {table.Key} where IsDelete = 1 OR IsDelete = null",
AccessPermission.Allow
);
}
}
推荐阅读
- css - 我不知道为什么我的刻度在手机上是灰色的
- jsf - 我如何选择 SelectOneMenu 中默认显示的值
- firebase - 动态链接 Firebase
- asp.net-core - 如何使用 ILogger 在我的 ASP.NET Core 应用程序的 nuget 包中记录 serilog 发出的消息
- vue.js - vue.js 路由器 NavigationDuplicated 用于查询更改
- highcharts - Highcharts - yAxis 对数刻度和 allowDecimals 设置为 false 似乎没有任何效果
- spring-boot - 在外部tomcat上调用@GetMapping“/”会引发错误-Spring Boot
- java - 使用proguard构建应用程序时出现Android异常
- spring - JPA stream() 会导致 OutOfMemoryError 吗?
- java - 循环中的内循环与 Thymeleaf 中的组合 th:field