通用c#属性类型
发布时间:2020-12-15 22:27:32 所属栏目:百科 来源:网络整理
导读:我有三个类,其中两个继承自基类,第三个我想引用另外两个中的一个,具体取决于应用程序的状态. public class Batch{ public Batch() { }}public class RequestBatch : Batch{ public RequestBatch(string batchJobType) : base(batchJobType) { } public overr
我有三个类,其中两个继承自基类,第三个我想引用另外两个中的一个,具体取决于应用程序的状态.
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |