通用 c# 属性类型

本文关键字:类型 属性 通用 | 更新日期: 2023-09-27 18:35:15

我有三个类,其中两个继承自基类,第三个我想根据应用程序的状态引用另外两个类中的一个。

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'

有没有办法生成属性,以便它可以采用 Parent 类型的任何抽象?

谢谢!

通用 c# 属性类型

您显示的截图代码确实有效。没有编译器错误:

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 或任何派生类型。

一个选项...

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

另一个。。。

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

更多信息...

  • 泛型中的协方差和逆变
  • 逆变难题