简体   繁体   English

C#,Unity,需要帮助来制作字典<int, class>

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

I tried to look a bit about dictionaries and it should work, 我尝试看一下字典,它应该可以工作,

any idea why it doesn't? 知道为什么没有吗?

first I make a class with private properties: 首先,我制作一个具有私有属性的类:

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, in the class constructor, should I assign the private properties themself or through their get set methods? btw,在类构造函数中,我应该自行分配私有属性还是通过其get set方法分配私有属性?

anyway, then on another script, I make a dictionary: 无论如何,然后在另一个脚本上,我做了一个字典:

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

which gives me a bunch of error including : 这给了我很多错误,包括:

the level type argument doesn't take 0 arguments 级别类型参数不带0个参数

use parentheses instead of curly braces, because you want to pass values to the constructor. 使用括号而不是大括号,因为您要将值传递给构造函数。 curly braces is used for object-initializers. 花括号用于对象初始化程序。

new level("Green Field Forever", 1)

Another way of doing this is to use object initializer with property names that you want to set: 这样做的另一种方法是将对象初始值设定项与要设置的属性名称一起使用:

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

Note: As @ken2k mentioned in comments you need a parameterless constructor to use object initializers. 注意:正如@ ken2k在注释中提到的那样,您需要一个无参数的构造函数才能使用对象初始化程序。 since you have added a constructor to your class that takes some parameters, the default constructor will be ignored. 由于已在类中添加了带有某些参数的构造函数,因此默认构造函数将被忽略。 you need to add that manually like this: 您需要像这样手动添加:

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

should be 应该

new level("Golden Vally", 2) }

Also have a look to C# feature called auto implemented properties that was introduced in the version 3.0 of the language that came with .Net 3.5 (so it's available in any IDE that supports this version of the language). 还可以查看C#功能(称为自动实现的属性) ,该功能是.Net 3.5随附的语言3.0版中引入的(因此,在支持该语言版本的所有IDE中都可用)。

And generally speaking you should not set a value for the backing field associated with your property. 而一般来说,你应该设置你的属性相关联的支持字段的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM