[英]How do I create instance of class implementing generic interface with base type
Lets say I have this: 可以说我有这个:
public class BaseEntity {}
public class Product : BaseEntity {}
public interface IPreLoad<T> where T : BaseEntity
{
void Preload();
}
public class ProductService : IPreload<Product>
{
public void Preload()
{
//Do something
}
}
//Returns list of types implementing IPreload<>
var preloaders = typeFinder.FindClassesOfType(typeof(IPreLoad<>)).ToList();
foreach (var preloaderType in preloaders)
{
var preloader = (IPreLoad<BaseEntity>)EngineContext.Current.ResolveUnregistered(preloaderType);
cacheManager.Get(preloader.PreLoadCacheKey, () => preloader.PreLoad());
}
The issue I have is that I can't cast a ProductService : IPreLoad<Product>
to a IPreLoad<BaseEntity>
and I don't know how else I can cast this to achieve the same result. 我遇到的问题是我无法将
ProductService : IPreLoad<Product>
转换为IPreLoad<BaseEntity>
而且我不知道如何将其转换为相同的结果。 Basically, I want to create an instance of this service and call preload. 基本上,我想创建此服务的实例并调用preload。
Not performing the cast works fine and it creates an instance but then as I haven't cast it as anything, I can't make any calls to it based on the interface. 不执行强制转换效果很好,它会创建一个实例,但是由于我还没有将其强制转换为任何实例,因此无法基于该接口对其进行任何调用。
Your interface should be covariant: 您的接口应该是协变的:
public interface IPreLoad<out T> where T : BaseEntity
{
void Preload();
}
Then, assigment will be ok: 然后,可以进行分配:
IPreLoad<BaseEntity> preLoader = new ProductService();
In your example, The Preload Method is not affected by the generic type T, you could use a non generic interface like 在您的示例中,Preload方法不受通用类型T的影响,您可以使用非通用接口,例如
public interface IPreLoad
{
void Preload();
}
public interface IPreLoad<T>: IPreload where T : BaseEntity
{
// your other typed methods...
}
then you cast your objects as IPreload
instead of IPreLoad<BaseEntity>
然后将对象转换为
IPreload
而不是IPreLoad<BaseEntity>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.