简体   繁体   中英

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.

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. If the caller passes a typo ( "database" instead of "Database" ) then this code will throw an exception. 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> )?

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.

Yes you are correct. Using Dictionary<enum, string> is probably best way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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