Identifying generic type of class using reflection

隐身守侯 提交于 2019-12-25 05:23:06

问题


Is there any way to detect the type specified in a generic parameter on a class?

For example, I have the three classes below:

public class Customer
{ }

public class Repository<T>
{ }

public class CustomerRepository : Repository<Customer>
{ }

public class Program
{
    public void Example()
    {
        var types = Assembly.GetAssembly(typeof(Repository<>)).GetTypes();
        //types contains Repository, and CustomerRepository
        //for CustomerRepository, I want to extract the generic (in this case, Customer)
    }
} 

For each of the repository objects brought back, I'd like to be able to tell what type is specified.
Is that possible?

EDIT

Thanks to @CuongLe, got this which is working, however looks messy.... (also help from resharper ;))

var types = Assembly.GetAssembly(typeof(Repository<>))
 .GetTypes()
 .Where(x => x.BaseType != null && x.BaseType.GetGenericArguments().FirstOrDefault() != null)
 .Select(x => x.BaseType != null ? x.BaseType.GetGenericArguments().FirstOrDefault() : null)
 .ToList();

回答1:


Assume you now hold the type of CustomerRepository by selecting from list of types:

var customerType = typeof(CustomerRepository).BaseType
                          .GetGenericArguments().First();

Edit: You don't need to trust Re-Sharper 100%. Since you do Where to select all type whose BaseType is not null, needless to check again in Select. For more, FirstOrDefault actually return null, this code is optimized:

 Assembly.GetAssembly(typeof(Repository<>))
                  .GetTypes()
                  .Where(x => x.BaseType != null)
                  .Select(x => x.BaseType.GetGenericArguments().FirstOrDefault())
                  .ToList();



回答2:


Try using GetGenericArguments.



来源:https://stackoverflow.com/questions/12462900/identifying-generic-type-of-class-using-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!