简体   繁体   中英

What can a person use instead of enum for an intellisense aware collection of strings?

Currently using an enum for a list of filenames in an application for the ability to use intellisense and to make sure the filename is one of the existing files (the enum prevents typos and having to remember each filename verbatim). There are currently 107 files in the enum. In order to get an audio file name the enum value ToString() method is used.

Now there is a situation where there needs to be some filenames added based on the result of a database call. This isn't possible with an enum and will require a lot of application restructuring to implement (changing all methods that take an enum to take a string).

What should have been done in the first place or is an enum the best option for this use case?

I'm not quite sure of the use case, but one consideration is resource files. You would get intellisense, and the added bonus of being able to change the file names per localisation.

See here for an example.

One way to do this would, indeed, be to simply list every file as a string constant. But that makes it frustrating to add new content, and if you ever wanted to add new sounds, you'd have to recompile and distribute the entire application .

Instead of that, consider listing your sound files in a single data file (XML, perhaps?). Inside your program, import the data as a string-key, string-value dictionary, where your keys are the name of the sound and the values are the filenames. Build a wrapper class to hold the dictionary so you can handle errors gracefully, and voila! You have access to your sounds, AND you can add and remove sounds from outside the code itself.

Plus, when you make your database call, all you need to do is add the additional sound data to your dictionary.

Maybe you need to create a static class with constant members.

static class FileNames
{
    public const string FirstFileName = "FirstFileName.txt";
    //and so on
}

In case for the database part (that isn't elaborated and leaves room for guesses) you can use a T4 template that generates a class in which there is a list of file names declared in the form above. The T4 template can make the database call during design time using regular ADO .NET code, then the result of the query can be used to output the file names and constant members.

It is very worth while to discover T4: check this link: http://msdn.microsoft.com/en-us/library/bb126445.aspx .

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