简体   繁体   中英

IValueConverter - Casting generic Collections

I want to create a type independent Converter for counting the elements in a collection with a generic type.

    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
    }
}

value in this case is a Collection of any type. The problem is to find the correct casting type and cast the object. What I want to have is something like

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

but this does not work. I also tried to use Object as generic type, but then I get an InvalidCastException. Is there any elegant way to do it?

Since IEnumerable<T> is covariant, you can use this.

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

From MSDN :

Type Parameters

out T

The type of objects to enumerate.

This type parameter is covariant . That is, you can use either the type you specified or any type that is more derived.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM