在开发MultiValueConverter时,我遇到了一个奇怪的错误。
我在上收到一个"无效铸造异常">
int frameSize = (int)values[0] ; // <-- thows InvalidCast Exception
老实说,我无法确定原因。
public class SizeConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values == null || values.Length <3 || values[2] == null || values[1] == null || values[0] == null)
return 0;
int numItems = (int)values[2];
int separatorSize = (int)values[1];
int frameSize = (int)values[0] ; // <-- thows InvalidCast Exception
int totalSeparatorSize = (numItems - 1) * separatorSize;
int remainingArea = frameSize - totalSeparatorSize;
return remainingArea / numItems;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
我在即时窗口中验证了转换器中的接收值[3]数组
`{object[3]}
[0]: 100
[1]: 2
[2]: 4`
这是调用代码MSTest[TestClass]:
[TestClass]
public class TestConverters
{
[DataRow(100, 2, 4)]
[DataTestMethod]
public void Test_Piece_Sizing(double frameSize, int separatorSize, int numItems)
{
var sizeConverter = new SizeConverter();
object[] values = new object[] { frameSize, separatorSize, numItems };
Assert.AreNotEqual(0,sizeConverter.Convert(values, typeof(int), null, System.Globalization.CultureInfo.CurrentCulture));
}
}
=================================================
================修复的C O D E是:====================
public class SizeConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values == null || values.Length <3 || values[2] == null || values[1] == null || values[0] == null)
return 0;
int numItems = (int)values[2];
int separatorSize = (int)values[1];
double frameSize = System.Convert.ToDouble(values[0]) ;
int totalSeparatorSize = (numItems - 1) * separatorSize;
int remainingArea = System.Convert.ToInt32(frameSize) - totalSeparatorSize;
return remainingArea / numItems;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
在测试用例中,frameSize
是double
,而不是int
。在Convert
方法中,将其更改为int
或强制转换为double
。
frameSize是一个double.just转换为double