簡體   English   中英

將泛型強制轉換為接口類型 - 無法將類型為“System.RuntimeType”的對象強制轉換為類型

[英]Casting generic to interface type - Unable to cast object of type 'System.RuntimeType' to type

我有一些像這樣的課程:

public class Customer
{ }

public interface IRepository 
{ }

public class Repository<T> : IRepository
{ }

public class CustomerRepository<Customer>
{ }

然后,根據這個問題的答案,我可以使用反射來獲取每個*存儲庫的泛型引用的類型列表:

我最終想要的是Dictionary<Type, IRepository>

到目前為止,我有這個:

Dictionary<Type, IRepository> myRepositories = Assembly.GetAssembly(typeof(Repository<>))
.GetTypes()
.Where(typeof(IImporter).IsAssignableFrom)
.Where(x => x.BaseType != null && x.BaseType.GetGenericArguments().FirstOrDefault() != null)
.Select(
    x =>
    new { Key = x.BaseType != null ? x.BaseType.GetGenericArguments().FirstOrDefault() : null, Type = (IRepository)x })
.ToDictionary(x => x.Key, x => x.Type);

但是,它不喜歡我的演員(IRepository)x
我收到以下錯誤:

無法將類型為“System.RuntimeType”的對象強制轉換為“My.Namespace.IRepository”。

你不能使用Type (IRepository) type

你可以使用Activator.CreateInstance創建對象CustomerRepository ,你也不需要使用Select ,而是直接使用ToDictionary ,代碼如下:

var myRepositories = Assembly.GetAssembly(typeof(Repository<>))
       .GetTypes()
       .Where(x => x.BaseType != null && 
                   x.BaseType.GetGenericArguments().FirstOrDefault() != null)

       .ToDictionary(x => x.BaseType.GetGenericArguments().FirstOrDefault(), 
                            x => Activator.CreateInstance(x) as IRepository );

如果x是一個System.Type對象,就像xtypeof(Repository<>) ,你不能像那樣強制轉換它。 Type不是實例化。

如果x沒有“free”類型參數,即如果x是非泛型或閉合泛型,那么(IRepository)Activator.CreateInstance(x)可能會創建一個x類型的對象。 但我不確定這是你需要的。 是否會有無參數的實例構造函數?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM