繁体   English   中英

通用c#属性类型

[英]Generic c# property type

我有三个类,其中两个继承自基类,第三个我想引用另外两个中的一个,具体取决于应用程序的状态。

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'下的红色波形

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

谢谢!

剪切你显示的代码确实有效。 没有编译器错误:

class Program
{
    static void Main()
    {
        var rj = new RunningJob();
        rj.Property = new Child1();
        rj.Property = new Child2();
    }
}
public class RunningJob { 
    public Parent Property { get; set; }
}
public class Parent {    }
public class Child1 : Parent {    }
public class Child2 : Parent {    }

此代码附带的唯一问题是Property属于Parent类型。 因此,您无法调用特定于Child1/Child2 这可以使用类RunningJob上的泛型类型参数的约束来完成:

public class RunningJob<TParent> where TParent : Parent
{
    public TParent Property { get; set; }
}

因此,现在确保PropertyParent类型或任何派生类型。

一种选择......

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

另一个...

如果您不需要修改集合,则只需从List<T>更改为IEnumerable<T>

更多信息...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM