当我尝试将使用方法item.ToDictionary()
b
的值插入到已经初始化它的Dictionary<string,IList<string>>
a
时,我收到此错误。
Cannot implicitly conver type System.Collection.Generic.Dictionary<string,List<string>> to System.Collection.Generic.Dictionary<string,IList<string>>
var b = item.ToDictionary();
我使用此函数创建b并尝试插入。
public class Example {
private Dictionary<string, IList<string>> a;
private string c;
private IList<string> d;
public Example()
{
d = new List<string>();
a = new Dictionary<string, IList<string>>();
}
public void getDictionary()
{
var b = c.ToDictionary(e=>c, f=>d.ToList());
a = b;
}
}
答案 0 :(得分:1)
将b定义为
var b = c.ToDictionary(e=>c, f=>(IList<string>)d);
答案 1 :(得分:0)
问题是d.ToList()返回List<string>
,因此b的类型为Dictionary<string, List<string>>
,与Dictionary<string, IList<string>>
不同。您可以将其强制转换为IList<string>
来解决问题:
public void getDictionary()
{
var b = c.ToDictionary(e => c, f => (IList<string>) d.ToList());
a = b;
}