문제

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top