gpt4 book ai didi

c# - IValueConverter 的最佳实践是什么?

转载 作者:太空狗 更新时间:2023-10-29 20:46:58 24 4
gpt4 key购买 nike

IValueConverter 的最佳实践是什么? : 可以将 Exception 放在 Convert 方法中还是应该返回“something”?

这是一个例子:

[ValueConversion(typeof(float), typeof(String))]
public class PercentConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || string.IsNullOrEmpty(value.ToString()))
return string.Empty;

if (value is float) //Edited to support CultureInfo.CurrentCulture,
return string.Format(culture, "{0:n}{1}", ((float)value) * 100, "%");

//** Is it ok to put Exception here or should I return "something" here? **
throw new Exception("Can't convert from " + value.GetType().Name + ". Expected type if float.");
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException("Converting back is not implemented in " + this.GetType());
}
}

最佳答案

如果转换失败(格式错误的值、类型...),返回 DependencyProperty.UnsetValue .

它表示转换器没有产生任何值,并且绑定(bind)使用 FallbackValue(如果可用)或默认值代替。

此外,为了安全起见,您应该使用特定于文化的转换或不变转换来转换数据。

关于c# - IValueConverter 的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4944553/

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