如何实例化泛型类 [英] How to instantiate generic classes

查看:83
本文介绍了如何实例化泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个界面:

public interface ICrawlService<T> where T : SocialPostBase
{
    Task<int> Crawl(int accountId, Disguise disguise, ISocialAccountRepository socialAccountRepository, ISocialRepository<T> socialRepository, ISocialCrawlJobRepository jobRepository, IInstrumentationRepository instrumentationRepository);
}

我的社交资源库是:

public interface ISocialRepository<T> where T : class
{
    IEnumerable<SocialPostCollection<T>> List { get; }
    Task Add(SocialPostCollection<T> entity, string type);

    Task AddPosts(List<T> entity, string type);

    void Delete(SocialPostCollection<T> entity);
    void Update(SocialPostCollection<T> entity);
    T Find(string profileName, MediaType type);
}

我正在寻找一种多态设计,因此可以将不同的类实例化为单个类型.像这样:

I am looking for a polymorphic design so I can instantiate different classes into a single type. Something like:

var socialRepo = new SocialRepository<Video>(configration.CosmosDBServiceEndpoint, configration.CosmosDBSecret, configration.CosmosDBDatabaseId);
var socialRepo2 = new SocialRepository<Post>(configration.CosmosDBServiceEndpoint, configration.CosmosDBSecret, configration.CosmosDBDatabaseId);

ICrawlService<SocialPostBase> crawlService;

crawlService = new CrawlYoutubeProfileService();
var id = await crawlService.Crawl(jobId, null, _socialAccountRepo, socialRepo, _socialCrawlJobRepo, instrumentationRepo);

crawlService = new CrawlAnotherProfileService();
var id2 = await crawlService.Crawl(jobId, null, _socialAccountRepo, socialRepo2, _socialCrawlJobRepo, instrumentationRepo);

但是它将不接受通用参数的基类,但出现以下错误.

However it will not accept the base class for the generic parameter, I get following error.

无法隐式转换类型 'SocialCrawlServices.CrawlYoutubeProfileService'到 "SocialCrawlServices.ICrawlService". 存在显式转换(您是否缺少演员表?)

Cannot implicitly convert type 'SocialCrawlServices.CrawlYoutubeProfileService' to 'SocialCrawlServices.ICrawlService'. An explicit conversion exists (are you missing a cast?)

那么您如何进行通用的多态设计?那不可能吗?

So how do you make a generic polymorphic design? Is that not possible?

推荐答案

那不可能吗?

Is that not possible?

不,有可能.您只需在ICrawlService中的通用参数之前添加out.

No, it's possible. You just need to add out before your generic parameter in ICrawlService.

public interface ICrawlService<out T> where T : SocialPostBase

请参见泛型中的协方差和相反方.

这篇关于如何实例化泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆