简体   繁体   English

如何用接口ID之类的替代枚举?

[英]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. 我认为ContentType枚举是多余的。 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 这实际上取决于您要完成的工作,但是我可能要看的一个选择是使用泛型,因此IProvider还是这样

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. 我的建议是,当您需要switchesif-else链时,应考虑将方法插入到现有的类层次结构中或创建一个新的类层次结构。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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