【问题标题】:Reading the property of my object from the user input从用户输入中读取我的对象的属性
【发布时间】:2019-01-02 20:17:37
【问题描述】:

我是编码初学者,英语不是我的母语。

请看一下这段代码和我的 cmets 好吗?

由于篇幅原因,我在课堂上省略了代码Player

我想知道我要写什么而不是Alex.damage = int.Parse(Console.ReadLine());

namespace ConsoleApp5
{
    class Player
    {
        private int _health = 100;

        public int health
        {
            get
            {
                return _health;
            }
        }

        public void damage (int _dmg)
        {
            _health -= _dmg;
        }
    }
}

class Programm
{
    static void Main(string[] args)
    {
         Player Alex = new Player();
         Console.WriteLine("Wie viel Damage soll ausgeteilt werden?"); // "How much 
        //damage should be done"
        Alex.damage = int.Parse(Console.ReadLine()); // there is the error 
        //"'damage' is a methodgroup, therfore an assigment is not possible"
        Console.WriteLine(Alex.health);
        Console.ReadKey();
    }
}

【问题讨论】:

  • 欢迎来到 SO。请添加Player类的代码。
  • 好吧,我猜应该是 Alex.damage(int.Parse(Console.ReadLine())); 和函数内部 damage 你会降低玩家的生命值
  • 感谢 Fabjan,它成功了。太明显了^^

标签: c# methods properties readline


【解决方案1】:

成员damage 是一个方法,因此您不能为其分配整数。

您需要做的是调用方法并将值作为参数传递。我建议先收集变量中的值。它使阅读和调试更容易:

var value = int.Parse(Console.ReadLine());
Alex.damage(value);

【讨论】:

    【解决方案2】:

    您能否详细说明需要实现的目标。如果您希望将值发送到损坏方法,您可以通过发送参数来调用该方法

         var damagefromuser=Convert.ToInt32(Console.ReadLine());
         Alex.damage(damagefromuser);
    

    如果你试图从方法中读取,你可以从方法中返回你想要的值

              public int damage (int _dmg)
            {
    
                  return _dmg;
            }
    

    【讨论】:

      猜你喜欢
      • 2020-04-08
      • 2019-12-06
      • 2020-06-24
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      相关资源
      最近更新 更多