创建一个通用字典从一个普通的列表
我尝试做以下,但我想我必须失去了一些东西...(相当新的仿制药)创建一个通用字典从一个普通的列表
(需要针对.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;
}
不幸的是,这给出了“非通用声明中不允许约束”的错误。有任何想法吗?
您尚未声明通用参数。
你的声明更改为:
public static Dictionary<string, T> ConvertToDictionary<T> (IList<T> myList) where T : IHasKey{
}
在这种情况下,使用“T where IHasKey”而不是声明Dictionary
@Mikael:通过这种方式,返回值是Dictionary
好点!但是,如果你想认真考虑输入列表可能包含IHasKey的不同实现,那么装箱是不可避免的。 – 2010-03-03 09:12:59
尝试是这样的
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);
你忘了通用放慢参数的方法
public static Dictionary<string, T> ConvertToDictionary<T>(IList<T> myList) where T: IHasKey
由于在输入列表中的类别不同(正如你在评论中所说的那样),你可以像@orsogufo建议的那样实现它,或者你也可以在inter上实现你的签名面对本身:
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;
}
使用通用的声明是最好的,如果你有一个具体的实施作为评论对方的回答指出接口的列表。
究竟是什么问题? – 2010-03-03 08:50:51
对不起,我已经把编译器错误信息放在帖子下面了。 – Damien 2010-03-03 08:55:38
你正在添加的项目,它们是同一个类,还是实现IHasKey的不同类? – 2010-03-03 09:09:43