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)
不幸的是,这给出了"非泛型声明不允许约束"错误.有任何想法吗?
您尚未声明泛型参数.
将您的声明更改为:
public static Dictionary<string, T> ConvertToDictionary<T> (IList<T> myList) where T : IHasKey{
}
Run Code Online (Sandbox Code Playgroud)