我想知道验证或强制执行用于字典对象/参数的 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/