将泛型强制转换为接口类型 - 无法将类型为"System.RuntimeType"的对象强制转换为类型

Ale*_*lex 7 c# reflection

我有一些像这样的课程:

public class Customer
{ }

public interface IRepository 
{ }

public class Repository<T> : IRepository
{ }

public class CustomerRepository<Customer>
{ }
Run Code Online (Sandbox Code Playgroud)

然后,根据这个问题的答案,我可以使用反射来获取每个*存储库的泛型引用的类型列表:

我最终想要的是一个 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);
Run Code Online (Sandbox Code Playgroud)

但是,它不喜欢我的演员(IRepository)x
我得到以下错误:

无法将类型为"System.RuntimeType"的对象强制转换为"My.Namespace.IRepository".

cuo*_*gle 11

你不能(IRepository) type用类型强制转换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 );
Run Code Online (Sandbox Code Playgroud)