【发布时间】:2011-02-09 11:58:58
【问题描述】:
- IValueConverter 的最佳做法是什么?
- 是否可以将异常放入 Convert 方法中,还是应该返回“某物”?
这是一个例子:
[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());
}
}
【问题讨论】:
-
IValueConverter 的最佳实践是什么?
-
@Amit:最好将关于异常的评论拉到前面的文本中。
-
我在代码中添加了注释! “可以把异常放在这里还是我应该在这里返回“东西”?”
-
相关问题:一段字符串有多长?