Skip to main content
 首页 » 编程设计

c#之c# 2.0(BindingList)中泛型缺少协变的解决方案

2024年02月24日15cloudgamer

这是一个设计问题。我有一个业务对象,以及从它派生的 5 个业务对象类型。

我还将有一个以 BindingList 作为成员的类。我将从中派生出 5 个类。

由于协变在这里不起作用,您将如何构 build 计以最大程度地减少代码重复?我当然可以放弃 BindingList 并使用 DataTable,这样问题就解决了。

但是既然每个人都对 BindingList 赞不绝口,我很想看看你们会如何处理这个问题。

解决方案(基于 Pavel Minaev 的回答):

public class SampleBase 
    { 
        protected string m_seq; 
        protected string m_id; 
        protected string m_weight; 
        protected string m_units;        
 
        public SampleBase(string seq, string id, string weight, string units) 
        { 
            Seq = seq; 
            Id = id; 
            Weight = weight; 
            Units = units; 
        } 
 
        public SampleBase() { } 
 
        public string Seq 
        { 
            get { return m_seq; } 
            set { m_seq = value; } 
        } 
 
        public string Id 
        { 
            get { return m_id; } 
            set { m_id = value; } 
        } 
 
        public string Weight 
        { 
            get { return m_weight; } 
            set { m_weight = value; } 
        } 
 
        public string Units 
        { 
            get { return m_units; } 
            set { m_units = value; } 
        } 
 
    } 
 
    public class FwdSample : SampleBase 
    { 
        protected string m_std_id; 
 
        public FwdSample() { } 
 
        public FwdSample (string seq, string id, string weight, string units, string std_id ) : base(seq, id, weight, units) 
        { 
            StdId = std_id; 
        } 
 
        public string StdId  
        { 
            get { return m_std_id; } 
            set { m_std_id = value; } 
        } 
    } 
    //End of Sample Classes 
 
 
 
 
 
    public abstract class RunBase<T> where T : SampleBase , new() 
    { 
        protected BindingList<T> m_samples; 
 
 
 
        public RunBase() {} 
 
        public void Add(T sample) 
        { 
            m_samples.Add(sample); 
        } 
 
        public void Update(int index, T sample) 
        { 
            m_samples[index] = sample; 
        } 
 
        public void Delete(int index) 
        { 
            m_samples.RemoveAt(index); 
        } 
 
 
 
        public BindingList<T> Samples 
        { 
            get { return m_samples; } 
        } 
    } 
 
 
    public class FwdRun : RunBase<FwdSample> 
    { 
 
        public FwdRun() 
        { 
            m_samples = new BindingList<FwdSample>(); 
        } 
 
 
    } 

请您参考如下方法:

假设您的 BindingList 成员是私有(private)的(或 protected ),并且没有以其他方式暴露在您的类 API 中,您可能需要这样的东西:

  class Base 
  { 
      // No BindingList here. All members that don't need it should be here 
      ... 
  } 
 
  class Base<TDerived> : Base where TDerived : Base<TDerived> 
  { 
       BindingList<TDerived> list = new BindingList<TDerived>(); 
 
       // All members that need BindingList should be here 
  } 
 
  class Derived1 : Base<Derived1> { ... } 
  class Derived2 : Base<Derived2> { ... } 
  ...