Creating a Generic Dictionary From a Generic List
I am t开发者_JAVA百科rying to do the following but I think I must be missing something...(fairly new to generics)
(Need to target .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;
}
Unfortunately, this gives a "Constraints are not allowed on non-generic declarations" error. Any ideas?
You have not declared the generic parameter.
Change your declaration to:
public static Dictionary<string, T> ConvertToDictionary<T> (IList<T> myList) where T : IHasKey{
}
Try something like this
public class MyObject : IHasKey
{
public string LookupKey { get; set; }
}
public interface IHasKey
{
string LookupKey { get; set; }
}
public static Dictionary<string, T> ConvertToDictionary<T>(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;
}
List<MyObject> list = new List<MyObject>();
MyObject o = new MyObject();
o.LookupKey = "TADA";
list.Add(o);
Dictionary<string, MyObject> dict = ConvertToDictionary(list);
You forgot the Generic Paramter in the method
public static Dictionary<string, T> ConvertToDictionary<T>(IList<T> myList) where T: IHasKey
Since the classes in the input list are different (as you say in your comment) you can either implement it like suggested by @orsogufo, or you could just as well implement your signature on the interface itself:
public static Dictionary<string, IHasKey> ConvertToDictionary(IList<IHasKey> myList)
{
var dict = new Dictionary<string, IHasKey>();
foreach (IHasKey item in myList)
{
dict.Add(item.LookUpKey, item);
}
return dict;
}
Using the generic declaration is best if you have a list of one specific implementation of the interface as noted in the comments to the other answer.
精彩评论