【问题标题】:Method usage between two classes两个类之间的方法使用
【发布时间】:2018-04-29 17:56:35
【问题描述】:

这是我的代码。我想用a.Quest() 方法增加速度值。这种方法属于第一类。第二类继承自第一类。

增加的方法是在二等舱,但我在一等舱使用它。这就是我想要做的。我不想在main里写这么多代码。

但是,当我运行程序时,a.Speedb.Speed 都等于零。我希望其中一个是 10 岁。我该如何解决这个问题?

    interface IElektroBeyin
    {
        int Speed{ get; set; } // Hız kontrolü
    }
    class AA : IElektroBeyin
    {
        public int Speed { get; set; }
        public virtual void GetFaster() { }
        public virtual void GetSlower() { }
        public  void Quest()
        {
            int x;                
            Console.WriteLine("Want to get faster ? 1- Yes");
            x = Console.Read();
            if (x == 1)
            {
                GetFaster();
            }
        }
    }
    class BB : AA
    {
        public override void GetFaster()
        {
               Speed += 10;
        }
        public override void GetSlower()
        {
                Speed -= 10;
        }
    }

    static void Main(string[] args)
    {
        BB b = new BB();
        AA a = new AA();
        a.Quest();
        Console.WriteLine(b.Speed);
        Console.WriteLine(a.Speed);
        Console.ReadLine();
    }
  }
}

【问题讨论】:

  • Console.Read 不读取整数,它为您提供读取字符的整数。您应该使用 Console.ReadKey 并使用 KeyChar 属性
  • 你在调用a.Quest,a属于AA类,AA中的虚方法不会增加Speed,所以什么也不会发生。你需要调用 b.Quest 来改变 b 中的速度。

标签: c# console-application


【解决方案1】:
AA a = new AA();
a.Quest();

AA.Quest() 调用AA.GetFaster(),但是这个方法是空的。这就是为什么当它被调用时什么都没有发生。 BB.GetFaster() 未被调用,因为它位于AA派生 类中。您可能希望反过来。

此外,要获取用户输入的数字,您不能使用Console.Read() 的返回值。使用int.Parse(Console.ReadLine()) 或类似的东西。

【讨论】:

    猜你喜欢
    • 2016-01-29
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2017-05-15
    • 2011-12-23
    相关资源
    最近更新 更多