![](/img/trans.png)
[英]Error 'Unable to cast object of type 'System.RuntimeType' to type 'EnvDTE80.DTE2'
[英]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
對象,就像x
是typeof(Repository<>)
,你不能像那樣強制轉換它。 Type
不是實例化。
如果x
沒有“free”類型參數,即如果x
是非泛型或閉合泛型,那么(IRepository)Activator.CreateInstance(x)
可能會創建一個x
類型的對象。 但我不確定這是你需要的。 是否會有無參數的實例構造函數?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.