簡體   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