C# 强制使用字典键

标签 c# dictionary standards

我想知道验证或强制执行用于字典对象/参数的 key 的最佳实践是什么。

以这个方法为例:

public override SqlServerQueryBuilder From(Dictionary<string, string> tableReferenceDictionary)
        {

            this.SelectQuery += " FROM " + this.IdentifierStart + tableReferenceDictionary["Database"] + this.IdentifierEnd
                             + "." + this.IdentifierStart + tableReferenceDictionary["Schema"] + this.IdentifierEnd
                             + "." + this.IdentifierStart + tableReferenceDictionary["Table"] + this.IdentifierEnd;

            return this;
        }

此方法采用 Dictionary 参数,并对所使用的键做出假设。如果调用者传递了一个拼写错误(“database”而不是“Database”),则此代码将引发异常。有没有更好的方法来管理这个问题?

也许不同的数据类型可以实现相同的效果?

也许使用枚举并将键设为枚举类型 ( Dictionary<enum, string> )?

最佳答案

这里的自定义类更合适,因此您可以强制所有“键”(将是新类中的属性)按预期填充。

关于C# 强制使用字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66145249/

相关文章:

javascript - 对象内部的 JS 方法 -> Swift

security - "disown-opener"内容安全策略指令有什么作用?

c# - 了解异常处理

c# - LINQ to sql 按方法的结果返回组

python - 从嵌套字典创建列表

python - 为什么 Python 的 sorted() 方法不会反转字典中具有相同值的键的顺序?

c# - 正则表达式匹配数字标记,但前提是不属于另一个单词的一部分

c# - SQL case 语句到更好的 C# 方法

c++ - 为什么 C++ 标准不更改 std::set 以使用 std::less<> 作为其默认模板参数?

function - 按要求次数执行功能