将整数赋值给double是非常合法的。为什么将整数分配给Double Attached Properties会产生错误?
如果我们能做到
double d = 3;
d分配3.0
但为什么失败的附加属性?
方案
我创建了一个附加属性
public static readonly DependencyProperty ActualWidthBeforeHidingProperty =
DependencyProperty.RegisterAttached("ActualWidthBeforeHiding",
typeof(double), typeof(MainWindow), new FrameworkPropertyMetadata(0));
public static double GetActualWidthBeforeHiding(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return Convert.ToDouble(element.GetValue(ActualWidthBeforeHidingProperty));
}
public static void SetActualWidthBeforeHiding(DependencyObject element, double value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(ActualWidthBeforeHidingProperty, value);
}
我编译的代码。没有编译时错误。
但是,当我试图运行应用程序它给了错误
在上面的代码我new FrameworkPropertyMetadata(0)
意外分配0和代码运行成功。
但我的印象是,你可以指定一个精度较低的数据类型(即整数)到一个具有更高精度的数据类型(即0.0双精度)?
那么为什么这种偏离基本编程概念的依赖属性呢?
你可能认为这是,但这不是。您必须分配预期的类型。如果是“双”,则分配3。0或(双)3。 – 2013-05-06 12:12:12
@ bash.d:我知道这是为什么。将整数赋值为double是合法的。 – 2013-05-06 12:14:14
我经常遇到这个错误,所以我最终编辑了我的依赖和附加属性的代码片段,以便默认值始终是'default($ type $)'... – 2013-05-06 12:23:18