简体   繁体   中英

Identifying generic type of class using reflection

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();

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();

尝试使用GetGenericArguments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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