gpt4 book ai didi

c#通用转换器

转载 作者:太空狗 更新时间:2023-10-29 23:14:48 24 4
gpt4 key购买 nike

我有一个转换器,可以让我在 SelectedItems 和 Generic List<MyType> 之间进行转换

public class SelectedTiposDocsToList : BaseConverter, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var Selecteditems = value as IList;
List<MyType> MyTypeList = Selecteditems.Cast<MyType>().ToList();
return MyTypeList;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

现在这对我来说是一个常见的任务,我想扩展这个类以允许泛型类型是这样的吗?

public class SelectedTiposDocsToList : BaseConverter, IValueConverter
{
public object Convert<T>(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var Selecteditems = value as IList;
List<T> MyTypeList = Selecteditems.Cast<T>().ToList();
return MyTypeList;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

这可能吗?如果是.. 如何在 XAML 上使用这种类型的转换器?

最佳答案

不,这不是 IValueConverter 的有效实现。但是,您可以在参数上传递一个类型:

{Binding MyVariable, Converter={StaticResource SelectedTiposDocsToList}, ConverterParameter={x:Type local:MyType}}

然后您将使用 SelectConvert.ChangeType 方法:MSDN

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var Selecteditems = value as IList;
var MyTypeList = Selecteditems.Cast<object>().Select((i) => System.Convert.ChangeType(i, parameter as Type)).ToList();
return MyTypeList;
}

已验证为在 VS 2013 上编译。

关于c#通用转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23749020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com