首页 > 解决方案 > 如何缩短 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 语句,这意味着有很多代码 &(复制/粘贴),我担心这会导致很多人为错误。

你有办法缩短这个吗?也许是循环类型的过程?

谢谢!

标签: c#

解决方案


好吧,你并没有真正提供足够的信息,但我会咬一口......假设你所有的表/代码都遵循相同的模式,它相当简单:

// 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
        );
    }
}

推荐阅读