儿童班:
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。我不明白为什么它不在这里工作。
答案 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)
声明你的成员在之外的构造函数:
public class Warrior:Inhabitant
{
private bool mobility;
private bool immortality;
// ...
}
将参数传递给新构造函数:
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
}
}