IValueConverter - 转换通用集合

时间:2014-01-05 17:24:42

标签: c# generics collections casting ivalueconverter

我想创建一个独立于类型的Converter,用于计算具有泛型类型的集合中的元素。

    public class CollectionCountConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return ((SomeCastingType)value).Count;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException(); // not used for oneway binding
    }
}
在这种情况下,

值是任何类型的集合。问题是找到正确的铸造类型并铸造对象。我想拥有的是像

Type t = value.GetType();
ICollection<t> c = (ICollection<t>) value;
int count = c.Count();

但这不起作用。我也尝试使用Object作为泛型类型,但后来我得到了InvalidCastException。有没有优雅的方法呢?

1 个答案:

答案 0 :(得分:0)

由于IEnumerable<T>是协变的,你可以使用它。

return ((System.Collections.Generic.IEnumerable<object>)value).Count();

来自MSDN

  

输入参数

     

out T

     

要枚举的对象类型。

     

类型参数是协变。也就是说,您可以使用任何一种类型   您指定的或任何更多派生的类型。