繁体   English   中英

如何获取继承的泛型类型

[英]How to get type of inherited generic

我有这些课程:

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

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

我怎样才能获得的类型CustomerService如果我有Customer在运行时类型?
它们都在同一名称空间中。
谢谢

如果你只是在寻找一个直接基类型是相关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];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM