2010-03-03 72 views
2

我尝试做以下,但我想我必须失去了一些东西...(相当新的仿制药)创建一个通用字典从一个普通的列表

(需要针对.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; 
} 

不幸的是,这给出了“非通用声明中不允许约束”的错误。有任何想法吗?

+2

究竟是什么问题? – 2010-03-03 08:50:51

+0

对不起,我已经把编译器错误信息放在帖子下面了。 – Damien 2010-03-03 08:55:38

+0

你正在添加的项目,它们是同一个类,还是实现IHasKey的不同类? – 2010-03-03 09:09:43

回答

6

您尚未声明通用参数。
你的声明更改为:

public static Dictionary<string, T> ConvertToDictionary<T> (IList<T> myList) where T : IHasKey{ 
} 
+0

在这种情况下,使用“T where IHasKey”而不是声明Dictionary 是什么意思? – 2010-03-03 08:59:59

+2

@Mikael:通过这种方式,返回值是Dictionary 而不是Dictionary ,所以当你访问这个值时,你可以避免额外的转换,并且确定你的字典包含哪些对象。 – 2010-03-03 09:04:07

+0

好点!但是,如果你想认真考虑输入列表可能包含IHasKey的不同实现,那么装箱是不可避免的。 – 2010-03-03 09:12:59

1

尝试是这样的

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 
0

由于在输入列表中的类别不同(正如你在评论中所说的那样),你可以像@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; 
} 

使用通用的声明是最好的,如果你有一个具体的实施作为评论对方的回答指出接口的列表。

+0

是的,但正如orsogufo指出的那样,这需要在从字典中检索后投射IHasKey对象以访问其他成员。 – Damien 2010-03-03 09:40:28

+0

但是如果输入列表的类型是IList ,我认为它是因为你有不同的类,所以你使用的实现没什么区别,因为如果你想用一个具体的类。 – 2010-03-03 09:43:08

+0

输入列表不一定是IList ,但如果是的话,那么您会是对的 – Damien 2010-03-03 10:27:30