0

我正在寻找一个返回构造字典的类。我不确定如何编写构造函数以返回字典,如何初始化与键配对的多个字符串值,我发现的唯一示例是非常粗略的草稿。这是一个粗略的例子:

namespace MyApp.Helpers
{
    public enum HouseSize
    {
        Big,
        Medium,
        Small
    }
    class Houses
    {
        public static Dictionary<HouseSize, string> _dictionaryOfHouses;

        public static Dictionary<HouseSize, string> Houses
        {
            get
            {
                if (_dictionaryOfHouses == null)
                    LoadHouses();
                return _dictionaryOfHouses;
            }
        }
    }
    private static void LoadHouses()
    {
        _dictionaryOfHouses = new Dictionary<HouseSize, string>;
        _dictionaryOfHouses.Add(HouseSize.Big, /*Add String Properties Here like Red, 2 Floor, Built in 1975*/);
        _dictionaryOfHouses.Add(HouseSize.Small, /*Add String Properties Here like Blue, 1 Floor, Built in 1980*/);
    }
}
4

3 回答 3

1

您可以使用List<string>而不是简单的string. 或者可能是另一个拥有以下属性的类:

class HouseProperties {
    public string Color { get; set; }
    public string YearBuilt { get; set; }  // I assume having these as strings is more
    public string NumFloors { get; set; }  // helpful then storing the number itself
}
于 2013-05-02T13:31:33.800 回答
0

首先返回的几件事Dictionary可能是一个问题,IDictionary会更好。

我会看类似的东西

private static void LoadHouses()
    {
        _dictionaryOfHouses = new Dictionary<HouseSize, Dictionary<string,string>;
        houseProperties = new Dictionary<String,String>();
        houseProperties.Add("Colour", "Red");
        // etc
        _dictionaryOfHouses.Add(HouseSize.Big, houseProperties);
    }

如果你觉得勇敢词典>

现在您可以输入其他属性

所以建造的年份可能是一个 int 和 Color 和 enum ..

建成后,您可以访问它

Houses[HouseSize.medium]["Colour"]
于 2013-05-02T14:06:20.237 回答
0

使用现有的房屋大小枚举:

public enum HouseSize {
    Big,
    Medium,
    Small
}

创建一个类来描述房屋的属性

public class HouseProperties {
    public string Colour { get; set; }
    public int NumFloors { get; set; }
    public int Year { get; set; }
}

// Create a Dictionary of House Sizes
// Use a List<HouseProperties> so you can have multiple houses
// of a house size, that can even have the same colour, number
// of floors and/or year
Dictionary<HouseSize, List<HouseProperties>> HouseDictionary = new Dictionary<HouseSize, List<HouseProperties>>();
// Initialize the House sizes
HouseDictionary.Add(HouseSize.Big, new List<HouseProperties>());
HouseDictionary.Add(HouseSize.Medium, new List<HouseProperties>());
HouseDictionary.Add(HouseSize.Small, new List<HouseProperties>());

// Adding a 2013 one-floor Mahogany Big House to the Dictionary
HouseDictionary[HouseSize.Big].Add(new HouseProperties() {
    Colour = "Mahogany",
    NumFloors = 1,
    Year = 2013
});
于 2013-05-02T14:27:28.033 回答