代码之家  ›  专栏  ›  技术社区  ›  Protector one reece

我可以用基类的实例初始化派生类吗?

  •  1
  • Protector one reece  · 技术社区  · 16 年前

    例子:

    public class MyList<T> : List<T> {
        public MyList(List<T> list) {
            this = list;  // this is basically what I want, but doesn't work
            base = list;  // this also doesn't work
        }
    }
    

    有什么解决办法吗?或者我想达到的只是一个坏主意?

    动机:我想向列表对象添加一个自定义函数。

    4 回复  |  直到 16 年前
        1
  •  1
  •   Paul Manzotti    16 年前

    你不能这样做:

    public MyList(List<T> list) : base(list)
    

    或者,您不能在列表对象上使用扩展方法吗?

        2
  •  3
  •   bristows    16 年前

    如果您使用.NET Framework 3.5,那么在列表中定义扩展方法就不容易了。比如…

    public static class MyListExtensionClass
    {
        public static void MyList<T>(this List<T> list)
        {
            // Your stuff
        }
    }
    
        3
  •  0
  •   Alexander Vakrilov    16 年前

    公共mylist(列表列表):base(列表)

    这将调用基类的以下构造函数(在本例中为列表):

    public List(IEnumerable<T> collection);
    
        4
  •  0
  •   Antony Koch    16 年前
    public class MyList<T> : List<T>
    {
      public MyList(List<T> list)
      {
        AddRange(list);
      }
    }