【问题标题】:How can I use generics to put this method in the parent class?如何使用泛型将此方法放在父类中?
【发布时间】:2010-11-01 19:11:28
【问题描述】:

我有许多 plural item 类,每个类都有一个 singular item 类的集合,如下所示:

public class Contracts : Items
{
        public List<Contract> _collection = new List<Contract>();
        public List<Contract> Collection
        {
            get
            {
                return _collection;
            }
        }
}

public class Customers: Items
{
        public List<Customer> _collection = new List<Customer>();
        public List<Customer> Collection
        {
            get
            {
                return _collection;
            }
        }
}

public class Employees: Items
{
        public List<Employee> _collection = new List<Employee>();
        public List<Employee> Collection
        {
            get
            {
                return _collection;
            }
        }
}

我可以想象我可以使用泛型来把它放到父类中。我怎么能这样做,我想它看起来像这样:

伪代码:

public class Items
{
        public List<T> _collection = new List<T>();
        public List<T> Collection
        {
            get
            {
                return _collection;
            }
        }
}

【问题讨论】:

    标签: c# generics inheritance


    【解决方案1】:

    完全正确,只是你还想在 Items 后面加上 &lt;T&gt;

    public class Items<T>
    {
            public List<T> _collection = new List<T>();
            public List<T> Collection
            {
                get
                {
                    return _collection;
                }
            }
    }
    

    实例化:

    Items<Contract> contractItems = new Items<Contract>();
    

    【讨论】:

      【解决方案2】:

      是的,尽管项目也必须是通用的。

      public class Items<TItem>
      {
          private IList<TItem> _items = new List<TItem>();
          public IList<TItem> Collection
          {
              get { return _items; }
          }
          // ...
       }
      

      让 Items 也从 IEnumerable&lt;TItem&gt; 继承可能是有意义的。

      【讨论】:

      • 如果 Items 继承自 IEnumerable,我能以某种方式在 foreach 循环中使用 Items 吗?我正在寻找一种方法来做到这一点。
      • 是的,你可以使用 foreach (严格来说你只需要一个 GetEnumerator,但你也可以正确实现 IEnumerable)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多