按id的接口实例

问题描述 投票:-1回答:2

我们有不同类型的图像,我们将图像存储在相应的子文件夹中,以及数据库中的元数据,包括fileTypeId。目前我们有这个:

public enum FileTypes
{
    Document=1,
    ProfileProto
    ...
}

switch (fileType)
   case 1:
        subdir = "documants"
   case 2:
        subdir = "profilephotos
   default: ...error...

这样的事情

这违反了SOLID的开/关原则

所以我尝试创建它:

public class DocumentFileType : IFileType
{
    public int Id => 1;
    public string Subfolder => "documents";
}

但问题是,当我们将图像的元数据存储到数据库中时,我们将该类型的id存储到数据库字段中。在这种情况下为1或2。因此,当我进行检索时,我应该做一些类似IFileType的文件类型= IFileType.instnceWithId(1)但当然这是不可能的。

我该怎么办呢?

c# enums interface solid-principles open-closed-principle
2个回答
0
投票

我会坚持使用Enum的简单解决方案并使用Attribute来使用子目录字符串来装饰它,以便在一个地方拥有所有需要的数据:

public enum FileTypes
{
    [SubDirectory("documents")]
    Document = 1,

    [SubDirectory("profilefotos")]
    ProfileFoto = 2 
}

0
投票

为了使代码更具可扩展性,我认为您需要某种存储所有已知文件类型的注册表。注册表可以是库的一部分并公开,以便外部代码可以注册自己的文件类型。

public class DocumentFileTypeRegistry 
{
    IDictionary<int, IFileType> _registeredFileTypes = new Dictionary<int, IFileType>();

    public void RegisterType(IFileType type)
    {
        _registeredFileTypes[type.Id] = type;
    }

    public IFileType GetTypeById(int id)
    {
        return _registeredFileTypes[id];
    }
}

public class DocumentFileType : IFileType
{
    public int Id => 1;
    public string Subfolder => "documents";
}

public class PhotoFileType : IFileType
{
    public int Id => 2;
    public string Subfolder => "photos";
}

然后你必须在你的注册表中注册Filetypes:

_fileTypeRegistry = new DocumentFileTypeRegistry();
_fileTypeRegistry.RegisterType(new DocumentFileType());
_fileTypeRegistry.RegisterType(new PhotoFileType());

//retrieve the type by id
var fileType = _fileTypeRegistry.GetTypeById(1);
© www.soinside.com 2019 - 2024. All rights reserved.