如何获取继承泛型的类型

本文关键字:继承 泛型 类型 获取 何获取 | 更新日期: 2023-09-27 18:19:57

我有这些类:

public abstract class BaseClass{}
public class CustomerService : BaseClass<Customer>{}
public class ProductService : BaseClass<Product>{}
public class UserService : BaseClass<User>{}

在运行时,我有这样的类型:entity.GetType(),它将返回泛型类型:例如Customer

如果我在运行时有Customer类型,我如何获得CustomerService的类型
它们都在同一个命名空间中
感谢

如何获取继承泛型的类型

如果你只是在寻找一个直接基类型为相关BaseClass<T>的类,你可以使用这样的代码:

var targetBaseType = typeof(BaseClass<>).MakeGenericType(entityType);
var type = typeof(BaseClass<>).Assembly.GetTypes()
                              .Single(t => t.BaseType == targetBaseType);

为了避免每次都进行线性搜索,您可能需要创建一个Dictionary<Type, Type>,其中键是实体类型,值是服务类型。您可以通过反射来设置它,也可以手动创建它。那么真的很简单:

var type = serviceTypeDictionary[entityType];