【发布时间】:2011-06-10 09:50:16
【问题描述】:
我有以下课程:
public class AuthContext : DbContext
{
public DbSet<Models.Permission> Permissions { get; set; }
public DbSet<Models.Application> Applications { get; set; }
public DbSet<Models.Employee> Employees { get; set; }
// ...
}
我为DbSet<T> 类型创建了扩展方法Clear()。使用反射,我能够检查AuthContext 的实例并将其所有DbSet<T> 类型的属性读取为PropertyInfo[]。如何将PropertyInfo 转换为DbSet<T> 以便在其上调用扩展方法?
var currentContext = new AuthContext();
...
var dbSets = typeof(AuthContext).GetProperties(BindingFlags.Public | BindingFlags.Instance);
dbSets.Where(pi =>
pi.PropertyType.IsGenericTypeDefinition &&
pi.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>)).ToList()
.ForEach(pi = ((DbSet<T>)pi.GetValue(currentContext, null)).Clear()); // !!!THIS WILL NOT WORK
【问题讨论】:
-
当您说
!!!THIS WILL NOT WORK时,您到底是什么意思?会发生什么 -
您能否发布您的
Clear()方法的签名(不需要正文)以帮助@Daniel Hilgarth 和我澄清一些事情:) -
我想知道
pi.PropertyType.IsGenericTypeDefinition怎么不会因为你而失败。见this
标签: c# generics reflection casting