我在这里错过了一些简单的东西,我知道。我的私有变量是“未分配”,而是来自我(有限)的知识。我错过了什么?我看过其他类似的问题,但我不太明白答案(甚至是问题!)。请帮忙。
public class Weapon
{
private string mName;
private double mRange;
private double mDamage;
public string Name
{
get { return mName; }
set { mName=value; }
}
public double Range
{
get { return mRange; }
set
{
if (value >= 0)
mRange=value;
else
throw new ArgumentException("Invalid Range");
}
}
public double Damage
{
get { return mDamage; }
set
{
if (value >= 0)
mDamage=value;
else
throw new ArgumentException("Invalid Damage");
}
}
public Weapon(string n, double d)
{
n = Name;
d = Damage;
}
public Weapon (string n, double r, double d)
{
n = Name;
r = Range;
d = Damage;
}
答案 0 :(得分:1)
你有向后的构造函数。
此:
public Weapon(string n, double d)
{
n = Name;
d = Damage;
}
public Weapon (string n, double r, double d)
{
n = Name;
r = Range;
d = Damage;
}
应该是这样的:
public Weapon(string n, double d)
{
Name = n;
Damage = d;
}
public Weapon (string n, double r, double d)
{
Name = n;
Range = r;
Damage = d;
}
答案 1 :(得分:0)
试试这个:
public class Weapon
{
private string _name;
private double _range;
private double _damage;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public double Range
{
get
{
return _range;
}
set
{
if (value >= 0)
_range = value;
else
throw new ArgumentException("Invalid Range");
}
}
public double Damage
{
get
{
return _damage;
}
set
{
if (value >= 0)
_damage = value;
else
throw new ArgumentException("Invalid Damage");
}
}
public Weapon(string n, double d)
{
Name = n;
Damage = d;
}
public Weapon(string n, double r, double d)
{
Name = n;
Range = r;
Damage = d;
}
}