问题
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