简体   繁体   English

带有设置者和获取者的银行帐户

[英]Bank account with setters and getters

So i have a exercise where i need to do a bank account program. 所以我有一个练习,需要做一个银行帐户程序。 The pure goal is for me to understand the setters/getters and therefore is pretty simple. 纯粹的目标是让我理解设置者/获取者,因此非常简单。

I want to write my private int money; 我想写我私人的int钱; that is only accessible over my public get/set int Money; 仅可通过我的公共get / set int Money访问; after i have that, i want to use a method, like withdraw, where i withdraw some of my money. 有了这些之后,我想使用一种方法,例如提款,从中提款。 Now i have the problem, when i do my withdraw method, it tells me: Since Konto.Konto(int) gives void back, there can be no return. 现在我遇到了问题,当我执行我的withdraw方法时,它告诉我:由于Konto.Konto(int)给出了void的返回,因此无法返回任何值。 (Its not the word for word explanation, its my translation. (不是逐字解释,而是我的翻译。

I have never set anything to void, so i don't see where my problem is. 我从来没有设置任何无效的东西,所以我看不出我的问题在哪里。 Thank you in advance for helping me. 预先感谢您对我的帮助。

Edit: My end goal is that if i press 1 i can set the amount of money i withdraw and my system prints me the value i have left. 编辑:我的最终目标是,如果我按1,我可以设置我提取的金额,我的系统会向我打印我剩下的值。 So i "feed" my method a withdraw number, said number gets substracted from my initial value and it returns me the value i have left. 因此,我向我的方法“提款”了一个提款编号,该编号从我的初始值中减去,然后返回我剩下的值。

namespace ConsoleApp1
{
    class Konto
    {
        private int money;
        public int Money
        {
            get
            {
                return this.money;
            }
            set
            {
                money = value;
            }

        }

        public Withdraw(int money)
        {
            return Money - money;
        }

    }
}

You're missing the return type on your Withdrawal method. 您在Withdrawal方法上缺少返回类型。 It should be 它应该是

public int Withdrawal(int money)
{
   //you weren't setting the money variable to the new amount
   Money -= money;
   return Money;
}

In C# only the class constructor doesn't need a return type. 在C#中,仅类构造函数不需要返回类型。 So 所以

class Konto
{
   public Konto()
   {...}
}

Is valid but all other methods needs to have a return type. 有效,但所有其他方法都需要具有返回类型。 Also, just as a matter of style/clean up. 另外,就样式/清理而言。 You don't need the private backing field. 您不需要私人支持字段。 If you want to initialize the amount in the account and only change it through withdrawal and deposit method you can do something like this. 如果您要初始化帐户中的金额,并且仅通过提款和存款方法进行更改,则可以执行以下操作。

class Konto
{
   public int Money {private set; get;}
   public Konto(int initialAmount)
   {
       Money = initialAmount;
   }

   public int Withdrawal(amount)
   {
      Money -= amount;
      return Money;
   }

   public void Deposit(int amount)
   {
      Money += amount;
   }
}

In this code Money can only be set from inside the class through methods that you create. 在此代码中,只能通过创建的方法从类内部设置Money。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM