将对象转换为列表<;基本类型>;而不是派生类型

本文关键字:类型 gt 派生 对象 转换 列表 lt | 更新日期: 2023-09-27 18:25:35

我正试图为派生类型编写一个通用转换器。

返回me派生类型,即List<DerivedType>

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    string text = string.Empty;
    if (value is List<BaseType>)
    {
        var v = value as List<BaseType>;
        var x = v.Select(c => c.Name);
        text = string.Join(", ", x);
    }
    return text;
}
DerivedType, BaseType are placeholders for classes
value = List<DerivedType>
targetType = string
parameter = null

将对象转换为列表<;基本类型>;而不是派生类型

这里是

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string text = string.Empty;
        IEnumerable source = value as IEnumerable;
        if (source != null)
        {
            var v = source.OfType<BaseType>();
            var x = v.Select(c => c.Name);
            text = string.Join(", ", x);
        }
        return text;
    }

使用这种方法,我们只需验证该值是否为集合IEnumerable,然后尝试检索BaseType的所有对象,其余保持不变。

另一种更简单的方法,感谢Sergey Brunov

    IEnumerable<BaseType> source = value as IEnumerable<BaseType>;
    if (source != null)
    {
        var x = source.Select(c => c.Name);
        text = string.Join(", ", x);
    }

其他方法可以包括通用类型的验证以验证相同的类型。