C#构造函数漏洞

时间:2016-03-16 19:54:22

标签: 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, 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重量的两倍。

Animal的代码部分:

 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;
    }

我试图避免这些问题,这就是为什么我在Tiger中添加了额外的双重字段。但是我需要Tiger's这样工作,动物应该有一个Weight属性。

1 个答案:

答案 0 :(得分:0)

好的,问题不是继承或静态方法。它只是setter和构造函数中的相同字符串:TotalWeight + = value;