通用c#属性类型

通用c#属性类型,第1张

概述我有三个类,其中两个继承自基类,第三个我想引用另外两个中的一个,具体取决于应用程序的状态. public class Batch{ public Batch() { }}public class RequestBatch : Batch{ public RequestBatch(string batchJobType) : base(batchJobTyp 我有三个类,其中两个继承自基类,第三个我想引用另外两个中的一个,具体取决于应用程序的状态.

public class Batch{            public Batch() { }}public class RequestBatch : Batch{    public RequestBatch(string batchJobType) : base(batchJobType) { }    public overrIDe int RecordCount    {        get { return lines.Count; }    }}public class ResponseBatch : Batch{           public ResponseBatch(string batchJobType) : base(batchJobType) { }    public ResponseBatch(int BatchJobRunID)    { }}

有时我有一个实例化Child1的实例,有时我需要Child2.但是,我有一个模型,我想传递我的应用程序,以保持一切在一个地方,但我想要一种方法来使属性,包含Child1和Child2通用,例如:

public class BatchJob {   public List<Batch> Batches { get; set; }}

然后再这样做

public List<RequestBatch> GetBatches(...) {}var BatchJob = new BatchJob();BatchJob.Batches = GetBatches(...);

但是,编译器对我大吼大叫说它不能隐式地将Child1转换为(它的基类型)Parent.

我在“= GetBatches(….”说“无法隐式地将类型’System.Collections.Generic.List’转换为’System.Collections.Generic.List’下的红色波形

有没有办法生成属性,所以它可以采取父类型的任何摘要?

谢谢!

解决方法 一种选择……

public new IEnumerable<RequestBatch> GetBatches(...) {    get     {        return base.GetBatches(...).OfType<RequestBatch>();    }}

另一个…

如果您不需要修改集合,那么只需从List< T>更改即可.到IEnumerable< T>

更多信息…

> Covariance and Contravariance in Generics
> A contravariance conundrum

总结

以上是内存溢出为你收集整理的通用c#属性类型全部内容,希望文章能够帮你解决通用c#属性类型所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1232001.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存