从通用列表创建通用字典

Dam*_*ien 2 c# generics dictionary list

我正在尝试做以下事情,但我认为我必须遗漏一些东西......(对于仿制药而言相当新)

(需要针对.NET 2.0 BTW)

interface IHasKey
{
    string LookupKey { get; set; }
}
...

public static Dictionary<string, T> ConvertToDictionary(IList<T> myList) where T : IHasKey
{
    Dictionary<string, T> dict = new Dictionary<string, T>();
    foreach(T item in myList)
    {
        dict.Add(item.LookupKey, item);
    }

    return dict;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这给出了"非泛型声明不允许约束"错误.有任何想法吗?

Pao*_*sco 6

您尚未声明泛型参数.
将您的声明更改为:

public static Dictionary<string, T> ConvertToDictionary<T> (IList<T> myList) where T : IHasKey{
}
Run Code Online (Sandbox Code Playgroud)

  • @Mikael:这样返回值是Dictionary <string,Something>而不是Dictionary <string,IHasKey>,因此当您访问该值时,可以避免额外的强制转换并确定字典包含哪些对象. (2认同)