Generic C # Property Type

I have three classes, two of which are inherited from the base class, and the third - I would like to refer to one of the other two depending on the state of the application.

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)
    { }
}

Sometimes I have an instance of Child1, and sometimes I need Child2. However, I have a model that I want to pass to my application to save everything in one place, but I want to create a property that contains the child elements of Child1 and Child2, for example:

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

And then do it

public List<RequestBatch> GetBatches(...) {}

var BatchJob = new BatchJob();
BatchJob.Batches = GetBatches(...);

However, the compiler yells at me, saying that it cannot implicitly convert Child1 to (its base type) Parent.

I get red squiggles under "= GetBatches (...." saying "Cannot implicitly convert the type" System.Collections.Generic.List "to" System.Collections.Generic.List "

, Parent?

!

+4
2

...

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

...

, List<T> IEnumerable<T>

...

0

, , . :

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; }
}

, , Property Parent .

+1

Source: https://habr.com/ru/post/1629243/


All Articles