c# - 将泛型转换为接口(interface)类型 - 无法将类型为 'System.RuntimeType' 的对象转换为类型

标签 c# reflection

我有一些像这样的类:

public class Customer
{ }

public interface IRepository 
{ }

public class Repository<T> : IRepository
{ }

public class CustomerRepository<Customer>
{ }

然后,根据 the answer to this question我可以使用反射来为我的每个 *Repository:

获取泛型引用的类型列表

我想要结束的是 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);

但是,它不喜欢我的 Actor (IRepository)x
我收到以下错误:

Unable to cast object of type 'System.RuntimeType' to type 'My.Namespace.IRepository'.

最佳答案

你不能将 (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 );

关于c# - 将泛型转换为接口(interface)类型 - 无法将类型为 'System.RuntimeType' 的对象转换为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12464611/

相关文章:

javascript - 如何使用 NVDA 屏幕阅读器读取工具提示?

c# - 列表类的类结构?

java - Spring中如何进行注解?

.net - 使用 .NET 配置数据类型上的反射构建动态生成的配置 UI

c# - Reflection.Emit 和 Parallel.ForEach

c# - 计算机重启后包含空值而不是 JSON 对象的文件

c# - 将枚举标志附加到循环中的参数(按位附加)

c# - 为什么HttpContext.AcceptWebSocketRequest函数获取实例会报错?

java - 当我通过反射创建对象时,如何重写 Java 中的方法?

c# - 如何使用反射将属性的值设置为 null