C#,Unity,需要帮助制作<int,class =“”> </int,>的字典

时间:2014-07-04 14:25:39

标签: c# dictionary unity3d

我试着看一下字典,它应该有效,

任何想法为什么不呢?

首先我创建一个包含私有属性的类:

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}}
};

这给了我一堆错误,包括:

level类型参数不带0个参数

2 个答案:

答案 0 :(得分:2)

使用括号而不是花括号,因为您想要将值传递给构造函数。花括号用于对象初始化器。

new level("Green Field Forever", 1)

另一种方法是使用您想要设置的属性名称的对象初始值设定项:

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

注意:正如评论中提到的@ ken2k,您需要一个无参数构造函数来使用对象初始值设定项。既然你已经为你的类添加了一个带有一些参数的构造函数,那么默认的构造函数将被忽略。你需要像这样手动添加:

public level() { }

答案 1 :(得分:1)

new level{"Golden Vally", 2}}

应该是

new level("Golden Vally", 2) }

另请参阅名为auto implemented properties的C#功能,该功能是在.Net 3.5附带的语言版本3.0中引入的(所以它可以在支持此版本语言的任何IDE中使用)。

一般而言,您应为与您的媒体资源相关联的支持字段设置值。