簡體   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