0
我想创建一个类型独立的转换器来计算具有泛型类型的集合中的元素。IValueConverter - 铸造通用集合
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。有没有优雅的方式来做到这一点?
这里涉及的* actual *类型是什么?大多数集合也实现了非泛型'ICollection'接口,这使得事情变得更简单了......你可以用它来代替吗? –
您也可以使用'IEnumerable
列表的实际类型是**列表 **,它正在使用ICollection接口强制转换!对不起,我是新来的C#... –
user2476294