簡體   English   中英

C#,Unity,需要幫助來制作字典<int, class>

[英]C#, Unity, need help making a dictionary of <int, class>

我嘗試看一下字典,它應該可以工作,

知道為什么沒有嗎?

首先,我制作一個具有私有屬性的類:

using UnityEngine;
using System.Collections;

public class level
{
    private string levelTitle;
    private int moneyValue;

    public string LevelTitle
    {
        get
        {
            return levelTitle;
        }

        set
        {
            levelTitle = value;
        }
    }

    public int MoneyValue
    {
        get
        {
            return moneyValue;
        }

        set
        {
            moneyValue = value;
        }
    }

    public level(string levelTitle, int moneyValue)
    {
        this.LevelTitle = levelTitle;
        this.moneyValue = moneyValue;
    }
}

btw,在類構造函數中,我應該自行分配私有屬性還是通過其get set方法分配私有屬性?

無論如何,然后在另一個腳本上,我做了一個字典:

public Dictionary<int, level> levels = new Dictionary<int, level>()
{
    {0, new level{"Green Field Forever", 1}},
    {1, new level{"Golden Vally", 2}}
};

這給了我很多錯誤,包括:

級別類型參數不帶0個參數

使用括號而不是大括號,因為您要將值傳遞給構造函數。 花括號用於對象初始化程序。

new level("Green Field Forever", 1)

這樣做的另一種方法是將對象初始值設定項與要設置的屬性名稱一起使用:

new level{ LevelTitle = "Green Field Forever", MoneyValue = 1}

注意:正如@ ken2k在注釋中提到的那樣,您需要一個無參數的構造函數才能使用對象初始化程序。 由於已在類中添加了帶有某些參數的構造函數,因此默認構造函數將被忽略。 您需要像這樣手動添加:

public level() { }
new level{"Golden Vally", 2}}

應該

new level("Golden Vally", 2) }

還可以查看C#功能(稱為自動實現的屬性) ,該功能是.Net 3.5隨附的語言3.0版中引入的(因此,在支持該語言版本的所有IDE中都可用)。

而一般來說,你應該設置你的屬性相關聯的支持字段的值。

暫無
暫無

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

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