【问题标题】:How to have a generic interface?如何拥有通用接口?
【发布时间】:2017-10-28 19:40:33
【问题描述】:

我想有一个数据访问层的接口,并为各种数据库(即MongoDb,SQL Server等)实现它

public interface IDataAccess
{
    Task InsertEntityAsync<T>(string collectionName, T entity) where T : IData;
    // the rest
}

对于特定的数据库:

public class MongoDbDataAccess : IDataAccess
{
    public Task InsertEntityAsync<T>(string collectionName, T entity) where T : IData
    {
        throw new NotImplementedException();
    }
}

例如,我可以让T 代替StudentEntity 类型,然后在InsertEntityAsync() 方法中将其转换为特定数据库接受的类型。

但是我希望我的方法是通用的,所以如果我传递StudentEntity,该方法首先将其转换为StudentDocument,然后将其保存在db中,如果我传递UniversityEntity,该方法将其转换为UniversityDocument然后保存它,你就明白了。

如何有一个通用的方法将每个数据转换为数据库接受的相应类型?

【问题讨论】:

  • 你的接口的意图是成为你可能使用的每个可能的数据库框架的接口,还是你可能在给定数据库上使用的每个实体类型的接口?
  • @ChrisThompson 他们俩
  • 我不太了解反对意见。这怎么太宽泛了?!

标签: c# interface


【解决方案1】:

似乎最直接的方法是为每种类型的实体提供转换信息,例如在每种类型中作为静态Dictionary&lt;TKey, TValue&gt;

public class StudentEntity : IData  
{  
  public static Dictionary<FieldInfo, string> ConversionInfo = new Dictionary<FieldInfo, string>
  {
    {fieldinfo1, "database column name 1"},
    {fieldinfo2, "database column name 2"},
    ...
  }
  ...
}

您可以在哪里使用Type.GetField() 获取字段信息。

在进行转换时,您应该遍历此字典以获取您需要考虑的所有字段。

我应该警告你,深入研究 System.Reflection(在 C#/.NET 中处理类似元编程的行为并在运行时分析类型的命名空间)可能会很快变得非常难看,所以尽量将其保持在最低限度您需要获取这些字段。

请注意,这是对如何使用此技术的粗略、基本描述,您需要根据它如何适合您的实际代码来找出确切的细节。

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    相关资源
    最近更新 更多