C#新手编写多账户转账程序时无法识别Transfer类及静态成员问题求助
问题根因
你遇到的“主方法识别不了Transfer类”的表象,本质不是编译器找不到这个类,而是主方法里访问的Transfer.newCheckBalance、Transfer.newSaveBalance根本不是Transfer类中定义的可访问成员。编译器找不到对应成员时会抛出对应错误,呈现出来的效果就像类没被正常识别一样。
具体问题拆解
- 变量定义范围错误
你在Transfers方法内部定义的newCheckBalance、newSaveBalance属于方法级局部变量,仅在该方法执行的短暂过程中存在,方法运行结束后就会被内存回收,既不属于Transfer类本身,也不可能在其他类中通过Transfer.变量名的方式访问。
同时原Transfers方法没有返回任何计算结果,哪怕手动调用这个方法,外部也拿不到转账后的余额值。 - 转账逻辑未被触发
目前主方法仅完成了用户输入的读取,从未调用Transfer类里的余额计算逻辑,即使类结构正确,也无法得到转账后的余额结果。
修正步骤
- 调整Transfer类结构:将需要在主方法中读取的余额结果定义为类的公开静态字段,把原来的私有计算方法修改为可更新这些字段的公开静态方法。
- 在主方法读取完用户输入的转账金额后,手动调用Transfer类的计算方法,传入当前的支票余额、储蓄余额、转账金额,完成余额计算。
修正后的可运行完整代码
using System; public class Program { public static void Main(string [] args) { string shouldContinue = "yes"; Console.WriteLine("Welcome to the savings calculator!"); Console.WriteLine("Before we begin, we just need some information."); while(shouldContinue == "yes") { BankAccount myAccount = new BankAccount(); Console.WriteLine("How much is in your checking account today?"); myAccount.Checking = Int32.Parse(Console.ReadLine()); Console.WriteLine(); Console.WriteLine("How much is in your savings account today?"); myAccount.Savings = Int32.Parse(Console.ReadLine()); Console.WriteLine(); Console.WriteLine("How much would you like to transfer today?"); myAccount.Balance = Int32.Parse(Console.ReadLine()); Console.WriteLine(); // 调用转账计算逻辑 Transfer.ExecuteTransfer(myAccount.Checking, myAccount.Savings, myAccount.Balance); Console.WriteLine("The new balance in the checking account is: " + Transfer.newCheckBalance); Console.WriteLine(); Console.WriteLine("The new balance in the savings account is " + Transfer.newSaveBalance); Console.WriteLine(); Console.WriteLine("Would you like to continue?"); Console.WriteLine("Answer yes or no: " ); shouldContinue = Console.ReadLine(); } Console.WriteLine("Have a great day!"); } } class BankAccount { public int Checking; public int Savings; public int Balance; public int getChecking() { return this.Checking; } public void setChecking(int checkBalance) { this.Checking = checkBalance; } public int getSavings() { return this.Savings; } public void setSavings(int saveBalance) { this.Savings = saveBalance; } public int getBalance() { return this.Balance; } public void setBalance(int Balance2) { this.Balance = Balance2; } } class Transfer { // 类级别的公开静态字段,供外部读取计算后的余额 public static int newCheckBalance; public static int newSaveBalance; // 公开静态方法,接收账户信息和转账金额后完成计算 public static void ExecuteTransfer(int checkBalance , int saveBalance , int transferAmount) { newCheckBalance = checkBalance - transferAmount; newSaveBalance = saveBalance + transferAmount; } }
新手需要注意的规则
- 局部变量作用域:在方法大括号内定义的变量,仅能在当前方法内部使用,跨类、跨方法都无法直接访问
- 静态成员访问逻辑:只有被
public static修饰的类成员,才能通过类名.成员名的方式在其他类中访问 - 代码执行逻辑:类中写好的方法不会自动运行,必须在合适的位置手动调用,才会触发方法内的计算逻辑
内容的提问来源于stack exchange,提问作者newToThis
相关产品推荐
相关产品推荐

