使用自定义对象返回字典的C#类&多个字符串对

时间:2013-05-02 13:27:26

标签: c# class dictionary

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

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*/);
    }
}

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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);
    }

如果你感到勇敢的词典&gt;

现在您可以输入其他属性

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

在构建之后,您可以访问它

Houses[HouseSize.medium]["Colour"]

答案 2 :(得分:0)

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

public enum HouseSize {
    Big,
    Medium,
    Small
}

创建一个类来描述House的属性

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