简体   繁体   English

C# 强制使用字典键

[英]C# Enforcing Use of Dictionary Keys

I'm wondering what best practice is for verifying or enforcing the Keys used for a Dictionary object/parameter.我想知道验证或执行用于 Dictionary 对象/参数的键的最佳做法是什么。

Take for example this method:以这种方法为例:

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

This method takes a Dictionary parameter, and makes an assumption about the keys used.此方法采用 Dictionary 参数,并对所使用的键做出假设 If the caller passes a typo ( "database" instead of "Database" ) then this code will throw an exception.如果调用者传递了一个错字( “database”而不是“Database” ),那么此代码将引发异常。 Is there a better way to manage this?有没有更好的方法来管理这个?

Maybe a different data type that achieves the same thing?也许实现相同目标的不同数据类型?

Maybe use a enum and make the key of type enum ( Dictionary<enum, string> )?也许使用枚举并制作枚举类型的键( Dictionary<enum, string> )?

A custom class here is more appropriate, so you can enforce all your "keys" (which will be properties in the new class) are filled as expected.此处的自定义 class 更合适,因此您可以强制按预期填充所有“键”(将是新类中的属性)。

Yes you are correct.是的,你是对的。 Using Dictionary<enum, string> is probably best way to go.使用Dictionary<enum, string>可能是 go 的最佳方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM