質問

MSDN recommends that you use the OpenFileDialog class to allow the user to select one or more files if your program requires this functionality. The programmer can choose to add one or more filters to this dialog, so that only files with the extension that match the selected filter are displayed. This can be done by setting the OpenFileDialog.Filter property.

To do this, however, you must create a properly formatted string containing the the information the filter needs, like this:

dlg.Filter = "Supported Sound Files (*.flac, *.mp3)|*.flac;*.mp3|Flac files (*.flac)|*.flac|MP3 files (*.mp3)|*.mp3";

As more different filters are added, this quickly becomes rather messy.

My question is, why is this property a string that has to follow a specific format? What are the advantages of this, as opposed to, for instance, using a Dictionary<string, string[]>, where the first string is the name of the filter and the second name an array of file extensions supported by this filter, or something like that.

役に立ちましたか?

解決

My question is, why is this property a string that has to follow a specific format?

I suspect this is a throwback to the Windows API, where OPENFILENAME's lpstrFilter is effectively using this format, with a null character replacing the | characters, and two terminating null characters.

What are the advantages of this, as opposed to, for instance, using a Dictionary, where the first string is the name of the filter and the second name an array of file extensions supported by this filter, or something like that.

The main advantage here would purely be simplicity. A single string is far less code than a Dictionary<T,U> where the value is, itself, an object that needs construction (ie: a string[]). In general, file filters are typically not something that changes at runtime, so the string is effectively a constant that is determined once.

The disadvantage is having to work with "magic strings" of a strange format, of course.

It would be fairly easy to build something to handle this for you, though:

public static string BuildFileFilter(Dictionary<string, string[]> filters)
{
   return string.Join("|", 
                     filters.Select(kvp => kvp.Key 
                                           + "|" + string.Join(";", kvp.Value)));
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top