.Net中NameValueCollection的通用形式

Jee*_*van 5 .net c# generics

.Net是否提供NameValueCollection的通用形式或替代 Dictionary<string,List<T>>

就像是

Person john = new Person();
...
Person vick = new Person();
...

NameValueCollection<Person> stringToPerson = new  NameValueCollection<Person>();
stringToPerson.Add("John",john)
stringToPerson.Add("Vick",vick)
Run Code Online (Sandbox Code Playgroud)

实际上在我的情况下我被迫依赖Dictionary<string,List<Peron>>,还有其他选择吗?

此致,Jeez

Dan*_*Tao 3

据我所知,BCL 中没有内置这样的东西。我只会编写自己的类,它Dictionary<string, List<T>>在内部包装并公开适当的方法(例如,可以为给定的键Add添加一个元素)。List<T>

例如:

class NameValueCollection<T>
{
    Dictionary<string, List<T>> _dict = new Dictionary<string, List<T>>();

    public void Add(string name, T value)
    {
        List<T> list;
        if (!_dict.TryGetValue(name, out list))
        {
            _dict[name] = list = new List<T>();
        }

        list.Add(value);
    }

    // etc.
}
Run Code Online (Sandbox Code Playgroud)