簡體   English   中英

在 C# 中以 List 作為參數創建類的實例

[英]Creating instance of a class with List as a parameter in C#

您好我正在嘗試創建一個具有 3 個類的銀行應用程序 - 銀行、帳戶、主程序。 在我的主程序中,我可以選擇讓用戶添加一個新的銀行賬戶。 在我的銀行類中,我有我的屬性、構造函數和添加帳戶方法。

class Bank
{
    // Attributes

    private List<int> accounts { get; set; }
    private int number_of_accounts { get; set; }

    //Constructor
    public Bank(List<int> accounts, int number_of_accounts)
    {
        this.accounts= accounts;
        this.number_of_accounts = number_of_accounts;
    }
        public void AddNewAccount(int accountNumber)
    {
        accounts.Add(accountNumber);
        Console.WriteLine("Account with number " + accountNumber+ "has been added!");
    }

在我的主目錄中,我有一個菜單,用戶可以在其中選擇 1.在我調用我的方法的地方添加帳戶。

public static bool MainMenu()
        {
            Bank myBank = new Bank(accounts, 0); <----- Error here,

            switch ()
            {
                case "1":
                    // Function
                    Console.WriteLine("Write the account number desired:");
                    int userInput= Convert.ToInt32(Console.ReadLine());
                    myBank.AddNewAccount(userInput);
                    return true;
                case "2":
                    // Function

我的 MainMenu 中的第 3 行顯示“當前上下文中不存在名稱‘accounts’”。

問題是“帳戶”不存在,您還沒有創建任何名為帳戶的變量。 要解決此問題,請執行以下操作:

var accounts = new List<int>(); 
Bank myBank = new Bank(accounts, 0);

或者

Bank myBank = new Bank(new List<int>(), 0);

您可以在類中使用默認構造函數,如下所示:

class Bank
{
    public Bank()
    {
        this.accounts = new List<int>();
        this.number_of_accounts = 0;
    }
    ... rest of code (from your original question)
}

你必須注意一些事情:

通常private用於字段,而不是屬性。 您可以完全控制您的私有字段,因此通常您不會將其定義為私有屬性。

private readonly List<int> accounts;
private int number_of_accounts;

此外, number_of_accounts是多余的。 這是accounts.Count 因此,如果您在修改帳戶時忘記更新number_of_accounts ,最好使用accounts.Count並避免出現問題。

number_of_accounts必須是public的(並且是一個屬性而不是一個字段,因為它是公共的)並且只能使用get (沒有set ,因為您不能直接更改大小,您可以插入或刪除值)。

public int number_of_accounts => accounts.Count;

您不需要具有帳戶列表的構造函數。 只需創建列表。 稍后,使用AddNewAccount類的方法,您可以添加元素。

public Bank()
{
    this.accounts= new List<int>();
}

如果需要,您可以擁有一個帶有初始值列表的構造函數。 但請避免使用該列表,因為在外部,您的代碼可以修改該列表,最好讓您的類完全控制它們的字段。

public Bank(List<int> accounts)
{
    this.accounts= new List<int>();
    this.accounts.AddRange(accounts);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM