代码之家  ›  专栏  ›  技术社区  ›  James

C#-构造函数和继承

  •  3
  • James  · 技术社区  · 17 年前

    我有两个类是这样声明的:

    class Object1
    {
        protected ulong guid;
        protected uint type;
    
        public Object1(ulong Guid, uint Type)
        {
            this.guid = Guid;
            this.type = Type
        }
        // other details omitted
    }
    
    class Object2 : Object1
    {
        // details omitted
    }
    

    在客户端代码中,我希望能够像这样创建每个对象的实例:

    Object1 MyObject1 = new Object1(123456789, 555);
    Object2 MyObject2 = new Object2(987654321, 111);
    

    我如何让Object2像那样使用Object1的构造函数? 谢谢你。

    3 回复  |  直到 17 年前
        1
  •  9
  •   Frederik Gheysels    17 年前
    class Object2 : Object1
    {
       Object2(ulong l, uint i ) : base (l, i)
       {
       }
    }
    
        2
  •  1
  •   Garry Shutler    17 年前

    您必须为Object2提供一个具有相同签名的构造函数,然后调用基类的构造函数:

    class Object2 : Object1
    {
        public Object2(ulong Guid, uint Type) : base(Guid, Type) {}
    }
    
        3
  •  1
  •   Adam Ralph    17 年前

    给Object2一个构造函数,如下所示:-

    public Object2(ulong Guid, uint Type): base(Guid, Type)