[英]How do I create instance of class implementing generic interface with base type
可以说我有这个:
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());
}
我遇到的问题是我无法将ProductService : IPreLoad<Product>
转换为IPreLoad<BaseEntity>
而且我不知道如何将其转换为相同的结果。 基本上,我想创建此服务的实例并调用preload。
不执行强制转换效果很好,它会创建一个实例,但是由于我还没有将其强制转换为任何实例,因此无法基于该接口对其进行任何调用。
您的接口应该是协变的:
public interface IPreLoad<out T> where T : BaseEntity
{
void Preload();
}
然后,可以进行分配:
IPreLoad<BaseEntity> preLoader = new ProductService();
在您的示例中,Preload方法不受通用类型T的影响,您可以使用非通用接口,例如
public interface IPreLoad
{
void Preload();
}
public interface IPreLoad<T>: IPreload where T : BaseEntity
{
// your other typed methods...
}
然后将对象转换为IPreload
而不是IPreLoad<BaseEntity>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.