简体   繁体   中英

How to replace enumeration with something like interface ID?

Please consider the following interfaces:

interface IFile
{
    // Members
};

interface IAudioFile : IFile
{
    // Members
};

interface IVideoFile : IFile
{
    // Members  
};

enum ContentType
{
    Audio,
    Video
};

interface IProvider
{
    HashSet<ContentType> GetSupportedTypes();
    IList<IFile> GetFiles(ContentType contentType);
};

I think that ContentType enumeration is redundant. Is there any way to use something like interface identifier instead of enumeration type?

Any comments on the interface design are very appreciated.

It really depends on what you're trying to accomplish, but I one options you may want to look at is using generics, so that IProvider is as so

interface IProvider
{
    IList<IFile> GetFiles<T>() where T: IFile;
}

which can be implemented like so

public void ProviderConcrete()
{
    public IList<IFile> GetFiles<T>()
    {
        if(typeof(t) == typeof(IAudioFile))
            .... get Audio files

    }
}

and called like so

public void Caller()
{
    var files = GetFiles<IAudioFile>();
} 

Usually, it's better to write something like this:

void method(IFile file) {
    file.DoYourThing();
}

than

void method(ContentType id) {
   switch (id) {
   case ContentType.Audio: 
       file.DoThis();
       break;

   case ContentType.Video: 
       file.DoThat();
       break;
   }
}

That's because switches usually become a maintenance nightmare as time passes by, and it's error prone too.

My recommendation is that when you need switches or if-else chains you should consider to insert a method to an already existing class hierarchy or to create a new one. You should strive to write code that look like the one you see in the first code snippet.

As usual, this is generic so it may not apply to your particular problem at hand.

I think that the point here is that the returned list contains "base" objects.

If you don't like that, you could create some overloads like

IList<IAudioFile> GetAudioFiles();
IList<IVideoFile> GetVideoFiles();

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