为了账号安全,请及时绑定邮箱和手机立即绑定

更改存在于其他类中的变量

更改存在于其他类中的变量

C#
守着一只汪 2021-05-03 09:14:27
首先,我要感谢任何花时间研究此问题的人。我对C#相当陌生的问题是我需要声明一个类变量,该变量将存储用户的当前余额。它是一个类变量的原因是,它需要许多方法来访问。这是我第一次必须处理在其他类中存储变量的问题。如果有人知道如何更改存在于其他类中的变量,这将解决我的问题!private class Balance{    // (1) I'm not sure what to put here}private void buttonDeposit_Click(object sender, EventArgs e){    try    {        userInput = Convert.ToDecimal(textBoxUserAmount.Text);    }    catch    {        MessageBox.Show("Numbers only Please");        return;    }    //CheckDeposit is a boolean method checking if the users input is    //between certain numbers    if (CheckDeposit(check) == true)    {        // (2) here I want it to call Balance and += userInput but I        // have no idea how to     }    else    {        MessageBox.Show("Incorrect amount, make sure the input is between 20 and 200 inclusive");        return;    }}
查看完整描述

1 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

public class Balance

    {

    //Create variable with private access modifier

    private int _currentBalance;

    //Access it through property

    public int CurrentBalance{

    get

     {

       return _currentBalance;

     }

     set

      {

        _currentBalance = value;

      }

    }

}


    //Use it like


    balanceInstance.CurrentBalance += userInput

您还可以通过提供对属性的正确访问来限制用户。您可以将属性设置为可读或可写,或两者兼而有之。


根据评论更新:


需要公共类来访问整个项目中的公共财产。如果您要访问CurrentBalance项目中的任何位置,则可以创建类的实例并使用您的属性。


查看完整回答
反对 回复 2021-05-08
  • 1 回答
  • 0 关注
  • 164 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信