如何拥有通用接口? [英] How to have a generic interface?

查看:119
本文介绍了如何拥有通用接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to have one interface for data access layer, and implement it for various databases (i.e. MongoDb, SQL Server, etc)

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()方法转换它到该特定数据库接受的类型。

I could make T to be instead of type StudentEntity for example, and then inside InsertEntityAsync() method convert it to a type accepted by that specific database.

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

But I want my method be generic, so if I pass StudentEntity, the method convert it to StudentDocument first then save it in db, if I pass UniversityEntity, the method convert it to UniversityDocument then save it, and you get the idea.

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

How to have a generic method to convert each data to a corresponding accepted type by the database?

推荐答案

似乎最直接的方法是获取转换信息每种类型的实体,例如每种类型中的静态字典< TKey,TValue>

It seems that the most straightforward way to do this is to have a convert information for each type of entity, for example as a static Dictionary<TKey, TValue> inside each type:

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()

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

While doing the conversion, you should iterate through this dictionary to get all the fields you need to take into consideration.

我应该警告你挖掘System.Reflection(C#/ .NET中的命名空间处理类似元编程的行为并在运行时分析类型)可能会非常快速地变得非常丑陋,所以尽量将它保持在获得这些字段所需的最小值。

I should warn you that digging into System.Reflection (the namespace in C#/.NET that handles meta-programming-like behaviour and analyzing types at runtime) can get really ugly really fast, so try to keep it to the minimum you need to get those fields.

请注意,这是如何使用此技术的粗略,基本的描述,您需要根据它与实际情况的关系来确定具体细节代码。

Please note that this is a rough, basic description of how to use this technique, you'll need to figure out the exact details based on how it fits into your actual code.

这篇关于如何拥有通用接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆