绑定两个泛型类型

本文关键字:两个 泛型类型 绑定 | 更新日期: 2023-09-27 18:10:42

我有两个并行的类层次结构,其中第一个层次结构用于API,而第二个层次结构用于模型层。相同的类型在每个层次结构中都有一个表示(类),为了使用泛型,我想"绑定"(稍后会详细介绍)这两个类。

      API
     /   '
 ApiA     ApiB
     Model
     /   '
ModelA    ModelB

例如,一旦这个函数

public string DoSomething<APIType> (APIType value) {

获得一个apittype作为参数(例如ApiB),我想调用将一个ModelType作为类型参数(在本例中是ModelB)的关联泛型方法。

我尝试了类似的东西:public string DoSomething (ApiType value) where ModelType: Model where ApiType: API

但是我发现c#不能做部分推理,所以这个:

class ApiB : Api<ModelB> {}
ApiB obj;
DoSomething(obj) 

不能工作(需要两个类型参数)

我试图实现一些类似于c++的特性,但它没有工作。可以只使用Type,但我这样做是为了获得额外的编译器检查。

我想这不是一个大问题,但我想知道如果有人知道一个解决方案。

绑定两个泛型类型

这是个很复杂的问题。检查这段代码,我已经用List的通用构造函数代替了associated generic method的调用。如果你的问题和我从问题中理解的有不同,请评论。

class Program
{
    public class Model { }
    public class ModelB : Model { }
    public class Api<T> where T : Model
    {
        public List<T> CallGenericMethod()
        {
            return new List<T>();
        }
    }
    public class ApiB: Api<ModelB> { }
    public static string DoSomething<T>(Api<T> a) where T : Model
    {
        var b = a.CallGenericMethod();
        return b.GetType().ToString();
    }
    static void Main(string[] args)
    {
        ApiB a = new ApiB();
        Console.WriteLine(DoSomething(a));
    }
}

编辑两种类型的通用版本

public class Api<TApi, TModel> where TApi: Api<TApi, TModel> where TModel : Model
{
    public List<TModel> CallGenericMethod()
    {
        return new List<TModel>();
    }
}
public class ApiB: Api<ApiB, ModelB> { }
public static string DoSomething<TApi, TModel>(Api<TApi, TModel> a) where TApi : Api<TApi, TModel> where TModel: Model
{
    return new Dictionary<TApi, TModel>().GetType().ToString();
}