我在我的ASP.NET MVC應用程序中有一個接口/類,其中引用了所有我的通用存儲庫。這看起來是這樣的:在C#中使用反射和泛型屬性
public interface IDb
{
IGenericRepository<Car> CarRepository { get; }
...
IGenericRepository<User> UserRepository { get; }
}
我的目標是找到一個組件,它實現一定的接口,然後找到相應的通用存儲庫從數據庫中獲取某些對象的所有類型。這應該工作:
List<IVehicle> vehicleElements = new List<IVehicle>();
Type vehicleType = typeof(IVehicle);
Type dbType = typeof(IDb);
foreach (Type type in vehicleType.Assembly.GetTypes().Where(t => t.IsClass && t.GetInterfaces().Contains(vehicleType)))
{
PropertyInfo repositoryInfo = dbType.GetProperties().Where(p => p.PropertyType.GenericTypeArguments.Contains(type)).SingleOrDefault();
if (repositoryInfo != null)
{
var repository = repositoryInfo.GetValue(this.db);
// TODO: work with repository
}
}
return vehicleElements;
我的問題是,我不知道如何將資源庫變量轉換爲所需要的通用IGenericRepository ...任何想法?
你可以創建一個非泛型的'IRepository'並且(轉換爲和)與它一起工作。 –
您可以使用'dynamic'關鍵字.NET4。將var repository = repositoryInfo.GetValue(this.db);'更改爲'dynamic repository = repositoryInfo.GetValue(this.db);' – qujck