我有一些類是這樣的:鑄造通用的接口類型 - 無法投型「System.RuntimeType」的對象鍵入
public class Customer
{ }
public interface IRepository
{ }
public class Repository<T> : IRepository
{ }
public class CustomerRepository<Customer>
{ }
然後,按照the answer to this question我可以使用反射來獲取列表通過仿製藥我的每一個*庫的引用類型:
我想直到結束是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
我收到以下錯誤:
Unable to cast object of type 'System.RuntimeType' to type 'My.Namespace.IRepository'.
當你只有一個'Type'時,你期待*它得到一個實例嗎? –