【问题标题】:C# constructor flawC# 构造函数缺陷
【发布时间】:2016-03-16 19:54:22
【问题描述】:

这是我的代码的一部分:

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

看起来不错,但是当我创建一个实例并检查构造函数时,它显示的值是新猫体重的两倍。

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 像这样工作,Animals 绝对应该有 Weight 属性。

【问题讨论】:

  • 你真的不应该在静态变量中跟踪这些东西
  • 如果没有看到 Animal 的构造函数长什么样子,任何人都无法回答这个问题。

标签: c# constructor static-members


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-05-15
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 2011-04-03
    • 2010-12-16
    相关资源
    最近更新 更多