【问题标题】:c# Assigning a referencec# 分配引用
【发布时间】:2012-05-29 04:54:32
【问题描述】:

我对@9​​87654322@ 的Lab 有疑问,问题是我不确定如何分配我的参考。

这是我的代码:

class Bank
{
    static List<Account> accounts = new List<Account>();
    static Account active_account; // this will be an active 
    // Account (reference) retrieved from 
    // the bank. This will need to initialised either by 
    // CreateAccount or by RetrieveAccount.

    static void Main()
    {
        bool running = true, valid_option = false;
        int user_option = 0, account_num = 0, account_pin = 0;
        string name = "", type = "";
        decimal balance = 0, credit = 0;
        Bank chosen = new Bank();

        Console.Write("account number:");
                    account_num = SafeReadInteger(0);
                    Console.Write("pin number:");
                    account_pin = SafeReadInteger(0);
                    Console.Write("Client name:");
                    name = Console.ReadLine();
                    Console.Write("Balance:");
                    balance = SafeReadDecimal(0);
                    Console.Write("type:");
                    type = Console.ReadLine();
                    Console.Write("Credit:");
                    credit = SafeReadDecimal(0);
        chosen.CreateAccount(account_num, account_pin, name, balance, type);
    }
}

cmets来自讲师,

现在向下滚动到我的构造函数,

public Account CreateAccount(int ac_num_, int pin_, string owner_, decimal balance_, string type)
{
    Account newAcc = null;

    newAcc = new Account(ac_num_, pin_, owner_, balance_, type); // first uses the         constructor to create an account
    accounts.Add(newAcc); // second it inserts the account in the list and return the       reference to the account
    // depending on the type of account, a credit limit is set
    active_account = new Account(ac_num_, pin_);
    return newAcc;
}

我的问题是我在哪里初始化 active_account 以及我将它分配给什么?

【问题讨论】:

  • 我发现用尾随下划线标记方法参数的风格引人注目。是你的发明还是讲师口授的东西。还是您有某种推荐的样式引擎?

标签: c# initialization assign


【解决方案1】:

您的 CreateAccount 方法不是构造函数。这是一种工厂方法。它的工作原理是这样的:

active_account = chosen.CreateAccount(
    account_num, account_pin, name, balance, type);

active_account.DoStuff();

您的 Bank 实例有一个名为 CreateAccount 的工厂方法,该方法返回 Account 类的初始化实例。

【讨论】:

    【解决方案2】:

    看提供的代码,active_account是用来保存当前刚创建的活跃账户,或者是有人登录的时候。

    它正在您发布的 CreateAccount() 函数中进行初始化。同样,您的 RetrieveAccount() 函数将调用数据库并将 active_account 分配给一个新的 Account 对象。

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 2019-10-20
      • 2015-12-26
      • 2020-09-05
      • 1970-01-01
      相关资源
      最近更新 更多