相关疑难解决方法(0)

如何在C#4.0中实现通用协方差和Contra-variance?

我没有参加PDC 2008,但我听到一些消息称C#4.0被宣布支持Generic协方差和反差异.也就是说,List<string>可以分配给List<object>.怎么会这样?

在Jon Skeet的C#深度书中,解释了为什么C#泛型不支持协方差和反方差.它主要用于编写安全代码.现在,C#4.0改为支持它们.它会带来混乱吗?

有人知道有关C#4.0的细节可以给出一些解释吗?

c# covariance contravariance generic-variance c#-4.0

106
推荐指数
2
解决办法
4万
查看次数

KeyValuePair协方差

在这个例子中是否有更好的模仿协方差的方法?理想情况下我想做:

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)

有更好/更清洁的方式吗?

c# covariance c#-4.0 keyvaluepair

10
推荐指数
1
解决办法
892
查看次数

将对象转换为集合

我有一个情况,我得到一个对象,需要:

  • 确定该对象是单个对象还是集合(数组,列表等)
  • 如果它是一个集合,请通过列表.

到目前为止我有什么.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)

有人知道怎么做吗?

c# runtime type-conversion

3
推荐指数
1
解决办法
8351
查看次数