如何在将参数传递给父类构造函数时向子类构造函数添加更多代码?

时间:2017-02-17 14:15:41

标签: c# inheritance constructor

儿童班:

using System;
using System.Collections;
namespace Game
{
    public class Warrior:Inhabitant
    {
        public Warrior(string name,int age):base(name,age)
        {
            private bool mobility;
            private bool immortality;
        }
    }
}

现在是父类:

public class Inhabitant {

     private string name;
     private int age;

    public Inhabitant(string name,int age){
        this.name = name;
        this.age = age;
    }

此代码适用于Java。我不明白为什么它不在这里工作。

4 个答案:

答案 0 :(得分:2)

您需要声明私有字段并在构造函数

中初始化它们
using System;
using System.Collections;
namespace Game
{
    public class Warrior:Inhabitant
    {
        // declare private fields
        private bool mobility;
        private bool immortality;

        public Warrior(string name,int age, bool mobility, bool immortality):base(name,age)
        {
            // initialize
            this.mobility=mobility;
            this.immortality=immortality;
        }
    }
}

答案 1 :(得分:1)

  1. 声明你的成员之外的构造函数:

    public class Warrior:Inhabitant
    {
        private bool mobility;
        private bool immortality;
    
        // ...
    }
    
  2. 将参数传递给新构造函数:

    public class Warrior:Inhabitant
    {
        private bool mobility;
        private bool immortality;
    
        public Warrior(string name,int age, bool mobility, bool immortablity) : base(name,age) // base call as usual
        {
            // set properties
            this.mobility = mobility;
            this.immortability = immortability;
        }
    }
    

答案 2 :(得分:1)

首先,您不能将任何变量声明为私有内部构造函数或类的方法。

更改Warrior类如下,它应解决问题。

public class Warrior:Inhabitant
{
    private bool mobility;
    private bool immortality;
    public Warrior(string name,int age):base(name,age)
    {

    }
}

如果它们是构造函数的局部变量,那么应该声明它们没有访问修饰符。

public class Warrior:Inhabitant
{
    public Warrior(string name,int age):base(name,age)
    {
        bool mobility;
        bool immortality;
    }
}

答案 3 :(得分:0)

你不能在构造函数中使用访问修饰符。尝试:

public Warrior(string name,int age):base(name,age)
{
   bool mobility;
   bool immortality;
}

以上语法是正确的,但在语义上没有做任何事情,因为移动性和不朽性只存在于构造函数中。可能你想要像:

public class Warrior:Inhabitant
{
       private bool mobility;
       private bool immortality;
       public Warrior(string name,int age):base(name,age)
       {
            this.mobility=false; //example case
            this.immortality=true; //example case
       }
}