繁体   English   中英

在C#中使用反射和通用属性

[英]Work with reflection and generic properties in C#

我的ASP.NET MVC应用程序中有一个接口/类,其中引用了我的所有通用存储库。 看起来像这样:

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 ...有什么想法吗?

您要执行的操作无法正常工作,因为要拥有可靠的类型化存储库,您需要在编译时知道实现接口的类型。 但是您只在运行时知道它。

一种解决方案是引入非通用存储库。

另一种解决方案是使用dynamic关键字。

dynamic repository = repositoryInfo.GetValue(this.db);
repository.SomeMethod(...);

但是,这意味着编译器不再可以检查涉及此动态变量的代码。 换句话说:如果repository的实际类型上不存在SomeMethod ,则将引发运行时异常,而不是编译器错误。

我将使用基本的IRepository接口以及您需要在此代码中进行交互的常用方法。

如果由于某种原因无法实现,则可以采用松散耦合的方法,将其强制转换为动态方法,或者通过反射获取所需的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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