考慮以下(毫無意義,但它是用於說明目的)測試類:動態,LINQ和選擇()
public class Test
{
public IEnumerable<string> ToEnumerableStrsWontCompile(IEnumerable<dynamic> t)
{
return t.Select(x => ToStr(x));
}
public IEnumerable<string> ToEnumerableStrsWillCompile(IEnumerable<dynamic> t)
{
var res = new List<string>();
foreach (var d in t)
{
res.Add(ToStr(d));
}
return res;
}
public string ToStr(dynamic d)
{
return new string(d.GetType());
}
}
爲什麼它不與下面的錯誤編譯,在t.Select(x => ToStr(x))
?
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<dynamic>'
to 'System.Collections.Generic.IEnumerable<string>'. An explicit conversion
exists (are you missing a cast?)
第二種方法沒有錯誤。
+1用於解釋,特別是方法組版本 – 2011-05-04 07:54:13