如何使Dictionary成为工厂设计模式的通用IEnumerable

时间:2015-10-03 08:33:52

标签: c# wpf dictionary ienumerable factory

我正在开发一个使用XML数据的简单WPF电话簿应用程序。 我的想法是使它更通用,以便我可以使用SQL数据而不是XML数据 如果需要的话。这就是我选择基本工厂设计模式的原因。

这是我的界面(作为一个抽象类):

public interface IPhoneBookData
{
    Dictionary<string,string> GetPhoneBookData();
}

这是使用XML数据从该接口继承的Class 并返回字典:

using System.Collections.Generic;
using PhoneBook.BL.XML;
using PhoneBook.BL.XML.ParserXML;

public class PhoneBookDataXml : IPhoneBookData
{
    private string _path;
    Dictionary<string, string> _phoneBookDict = new Dictionary<string,    
                                                               string>();

    public PhoneBookDataXml(string path)
    {
        _path = path;
    }

    public Dictionary<string, string> GetPhoneBookData()
    {
        var phoneBookXml = ParseXml.Deserialize<PhoneBookXml>(_path);

        foreach (var item in phoneBookXml.Properties)
        {
            _phoneBookDict.Add(item.Key, item.Value);

        }

        return _phoneBookDict;
    }


}

这是我的工厂类:

public static class PhoneBookDataFactory
{
    public static IPhoneBookData GetPhoneBookClass(string input)
    {
        if (input.ToLower().Contains("xml"))
        {
            return new PhoneBookDataXml(input);
        }

        return null;
    }
}

最后这是使用工厂的MainViewModel类(WPF MVVM) 对于XML:

public MainViewModel()
{
    _nameList = new List<string>();
    _phoneList = new List<CustomKeyValuePair<string, string>>();

    //_phoneList = new List<string>();

    var PhoneBookDataInstance =              
                 PhoneBookDataFactory.GetPhoneBookClass("PhoneBook.xml");

    _phoneBookDict = PhoneBookDataInstance.GetPhoneBookData();

    _nameList = _phoneBookDict.Keys.ToList();
}

我知道Dictionary继承自ICollection,它继承自IEnumerable,但我尝试使它成为通用而且没有成功。

如果你能告诉我“GetPhoneBookData”怎么样,我会很感激的 将返回一个通用集合,我可以将其转换为字典或将来需要的任何其他集合。

2 个答案:

答案 0 :(得分:0)

您应该ICollection<KeyValuePair<string, string>>使用_phoneBookDict

ICollection<KeyValuePair<string, string>> _phoneBookDict = new Dictionary<string, string>();

IEnumerable<KeyValuePair<string, string>>作为方法GetPhoneBookData()

的返回类型
public IEnumerable<KeyValuePair<string, string>> GetPhoneBookData()
{
    var phoneBookXml = ParseXml.Deserialize<PhoneBookXml>(_path);

    foreach (var item in phoneBookXml.Properties)
    {
        _phoneBookDict.Add(new KeyValuePair<string, string>(item.Key, item.Value));
    }

    return _phoneBookDict;
}

答案 1 :(得分:0)

从你的问题不清楚到底究竟是什么,但由于Dictionary已经是ICollecion,你可以使用linq extesion方法将数据转换为其他类型。以下是一些例子:

转换为CustomKeyValuePairs列表

var phoneList = PhoneBookDataInstance
    .GetPhoneBookData()
    .Select(dictItem => new CustomKeyValuePair(dictItem.Key, dictItem.Value)
    .ToList();

转换为人物的ObservableCollection:

var persons = PhoneBookDataInstance.GetPhoneBookData()
    .Select(dictItem => new Person 
    {
        Name = dictItem.Key,
        Phone = dictItem.Value
    };

var observableCollection = new ObservableCollection<Person>(persons);

类似地,您可以转换为您需要的任何内容