首页 > 解决方案 > 从用户输入中读取我的对象的属性

问题描述

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

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

由于篇幅原因,我在课堂上省略了代码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();
    }
}

标签: c#methodspropertiesreadline

解决方案


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

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

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

推荐阅读