我有一些像这样的类:
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/