我没有参加PDC 2008,但我听到一些消息称C#4.0被宣布支持Generic协方差和反差异.也就是说,List<string>可以分配给List<object>.怎么会这样?
在Jon Skeet的C#深度书中,解释了为什么C#泛型不支持协方差和反方差.它主要用于编写安全代码.现在,C#4.0改为支持它们.它会带来混乱吗?
有人知道有关C#4.0的细节可以给出一些解释吗?
在这个例子中是否有更好的模仿协方差的方法?理想情况下我想做:
private IDictionary<string, ICollection<string>> foos;
public IEnumerable<KeyValuePair<string, IEnumerable<string>> Foos
{
get
{
return foos;
}
}
Run Code Online (Sandbox Code Playgroud)
但KeyValuePair<TKey, TValue>不是协变的.
相反,我必须这样做:
public IEnumerable<KeyValuePair<string, IEnumerable<string>>> Foos
{
get
{
return foos.Select(x =>
new KeyValuePair<string, IEnumerable<string>>(x.Key, x.Value));
}
}
Run Code Online (Sandbox Code Playgroud)
有更好/更清洁的方式吗?
我有一个情况,我得到一个对象,需要:
到目前为止我有什么.IEnumerable的测试不起作用.转换为IEnumerable仅适用于非基本类型.
static bool IsIEnum<T>(T x)
{
return null != typeof(T).GetInterface("IEnumerable`1");
}
static void print(object o)
{
Console.WriteLine(IsIEnum(o)); // Always returns false
var o2 = (IEnumerable<object>)o; // Exception on arrays of primitives
foreach(var i in o2) {
Console.WriteLine(i);
}
}
public void Test()
{
//int [] x = new int[]{1,2,3,4,5,6,7,8,9};
string [] x = new string[]{"Now", "is", "the", "time..."};
print(x);
}
Run Code Online (Sandbox Code Playgroud)
有人知道怎么做吗?