[英]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.