C#构造函数缺陷
以下是我代码的一部分:C#构造函数缺陷,c#,constructor,static-members,C#,Constructor,Static Members,以下是我代码的一部分: class Tiger: Animal,IPredator { private double weight; public static double AvgWeight; public static int Population; public static double TotalWeight; public Tiger(double aWeight):this(aWeight,"Savannah"){} public Tiger(double aWeight, pa
class Tiger: Animal,IPredator
{
private double weight;
public static double AvgWeight;
public static int Population;
public static double TotalWeight;
public Tiger(double aWeight):this(aWeight,"Savannah"){}
public Tiger(double aWeight, params string[] aHabitat) : base(aWeight,"Panthera Tigris", "Mammalia", aHabitat)
{
Population++;
TotalWeight += Weight;
AvgWeight = TotalWeight / Population;
Console.WriteLine($"Let's all welcome our new Tiger: {Weight} kilos. Average pride weight: {AvgWeight}");
}
public override double Weight
{
get
{
return weight;
}
set
{
TotalWeight -= weight;
weight = value;
TotalWeight += weight;
AvgWeight = TotalWeight / Population;
}
}
看起来不错,但当我创建一个实例并检查构造函数时,它显示的值是新cat的两倍
动物守则的一部分:
abstract class Animal
{
private string kind;
private string @class;
public List<string> Habitat = new List<string>();
public virtual double Weight { get; set; }
public string Kind { get { return kind; } set { } }
public string @Class { get { return kind; } set { Console.WriteLine("Class cannot be changed"); } }
public Animal(double aWeight,string aKind, string aClass,params string[] aHabitat)
{
kind = aKind;
@class = aClass;
Habitat.AddRange(aHabitat);
Weight = aWeight;
}
抽象类动物
{
私有字符串类;
私有字符串@class;
公共列表=新列表();
公共虚拟双权重{get;set;}
公共字符串种类{get{return Kind;}set{}
公共字符串@Class{get{return kind;}set{Console.WriteLine(“类不能更改”);}
公共动物(双aWeight,string-aKind,string-aClass,params-string[]aHabitat)
{
种类=同类;
@class=aClass;
栖息地:AddRange(aHabitat);
重量=重量;
}
我试图避免这些问题,这就是为什么我在Tiger中添加了一个额外的双字段。但是我需要Tiger的字段像这样工作,动物应该肯定有一个权重属性。好的,问题不在于继承或静态方法。它只是setter和构造函数中的同一个字符串:TotalWeight+=value;你真的需要吗不应该在静态变量中跟踪这些内容。任何人都不可能在不看到动物的构造函数的情况下回答这个问题。