【问题标题】:Customized list in C#C#中的自定义列表
【发布时间】:2011-11-24 14:17:14
【问题描述】:

我想在 C# 中创建自定义列表。在我的自定义列表中,我只想创建自定义函数 Add(T),其他方法应该保持不变。

当我这样做时:

public class MyList<T> : List<T> {}

我只能覆盖 3 个函数:EqualsGetHashCodeToString

当我这样做时

public class MyList<T> : IList<T> {}

我必须实现所有方法。

谢谢

【问题讨论】:

    标签: c# generics inheritance collections


    【解决方案1】:

    当我做 public class MyList : IList {}

    我必须实现所有方法。

    是的,但这很简单……只需将调用发送到原始实现即可。

    class MyList<T> : IList<T>
    {
        private List<T> list = new List<T>();
    
        public void Add(T item)
        {
            // your implementation here
        }
        
        // Other methods
    
        public void Clear() { list.Clear(); }
        // etc...
    }
    

    【讨论】:

    • “其他方法应保持不变”:这意味着在这种封装情况下,您也应该像开发人员一样映射所有 List 实现。只是因为有一个 Add() 自定义方法恕我直言似乎是一种奢侈。
    【解决方案2】:

    您可以让MyList 内部调用List&lt;T&gt; 实现,除了Add(T),您将使用Object Composition 而不是Class Inheritence,这也在GOF book 的前言中:"优先考虑‘对象组合’而不是‘类继承’。” (四人帮 1995:20)

    【讨论】:

      【解决方案3】:

      您可以再次使用 new 关键字:

      public class MyList<T> : List<T> 
      {
         public new void Add(T prm) 
         {
             //my custom implementation.
         }
      }
      

      Bad:你被限制使用的东西只有MyList类型。只有在 MyList 对象类型使用时,才会调用您自定义的 Add

      :有了这个简单的代码,你就完成了:)

      【讨论】:

        【解决方案4】:

        您可以为此使用装饰器模式。做这样的事情:

        public class MyList<T> : IList<T>
        {
            // Keep a normal list that does the job.
            private List<T> m_List = new List<T>();
        
            // Forward the method call to m_List.
            public Insert(int index, T t) { m_List.Insert(index, t); }
        
            public Add(T t)
            {
                // Your special handling.
            }
        }
        

        【讨论】:

          【解决方案5】:

          使用private List&lt;T&gt; 而不是继承,并根据需要实现您的方法。

          编辑:要让您的MyListforeach 循环,您只需添加GetEnumerator() method

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-04-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-10-12
            • 1970-01-01
            相关资源
            最近更新 更多