【问题标题】:Inheritance with different properties, how to write? [duplicate]不同属性的继承,怎么写? [复制]
【发布时间】:2019-08-01 02:15:03
【问题描述】:

我有一个带有 X 属性的 Animal 类和一个带有 B 属性的 Tiger 类。 Tiger 类继承自 Animal。在创建tiger类的实例时,Animal类的参数怎么放?

谢谢:)

class Program
    {
        static void Main(string[] args)
        {
            Animal dogA = new Tiger()
            dogA.Run();
            Console.ReadLine();
        }
    }
    class Animal
    {
        public int Age { get; set; }
        public string Color { get; set; }
        public float Speed { get; set; }

        public Animal(int age, string color, float speed)
        {
            Age = age;
            Color = color;
            Speed = speed;
        }
        public virtual void Run()
        {
            float runSpeed = (-1 * Speed) + 100;
            Console.WriteLine("I'm running at {0} kph", Speed);
        }
    }
    class Tiger : Animal
    {
        public int Legs { get; set; }

        public Tiger(int legs)
        {
            Legs = legs;
        }
        public override void Run()
        {
            double runSpeed = (Legs * Speed) / 2.5;
            Console.WriteLine("I'm running at {0} kph", Speed);
        }
    }

【问题讨论】:

标签: c# asp.net .net visual-studio xamarin


【解决方案1】:

更改子类中的构造函数,如

public class Tiger : Animal
{
    public int Legs { get; set; }

    public Tiger(int age, string color, float speed) : base(age,color,speed)
    {
        Legs = this.Legs;
    }
}

然后从Tiger类创建实例

   Tiger dogA = new Tiger(3, "red", 2.3f);
   dogA.Age = 12;
   dogA.Color = "Brown";
   dogA.Speed = 2.3f;
   dogA.Legs = 4;
   dogA.Run();

结果:I'm running at 3.67999992370605 kph

【讨论】:

  • Legs = this.Legs 将创建一个获取和设置属性的无限循环。相反,构造函数中应该有一个legs 参数。
猜你喜欢
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多