在 WPF 中,与值类型一起使用时 DependencyProperty 是否会导致大量装箱/拆箱?
在 WPF 中,与值类型一起使用时 DependencyProperty 是否会导致大量装箱/拆箱?或者实现是否有一些方法来防止这种情况而不是装箱/拆箱值类型?那么他们是如何做到这一点的呢?
我认为值类型是 DependencyPropertys 的主要用例。
谢谢
public double Price
{
get { return (double)GetValue(PriceProperty); }
set { SetValue(PriceProperty, value); }
}
public static readonly DependencyProperty PriceProperty =
DependencyProperty.Register("Price", typeof(double), typeof(Quote), new UIPropertyMetadata(0.0d));
In WPF do DependencyProperty's cause lots of boxing/unboxing when used with value types? Or does the implementation some how to prevent this and not box/unbox value types? Is so how do they do this?
I think value types are a major use case for DependencyPropertys.
Thanks
public double Price
{
get { return (double)GetValue(PriceProperty); }
set { SetValue(PriceProperty, value); }
}
public static readonly DependencyProperty PriceProperty =
DependencyProperty.Register("Price", typeof(double), typeof(Quote), new UIPropertyMetadata(0.0d));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简短的回答是肯定的。
依赖属性值的下划线存储没有值类型的概念,并将所有内容存储为对象,这将导致装箱。该框架本身通过辅助类 BooleanBoxes 使用“聪明的技巧”进行布尔属性存储优化,该类将 true 和 false 值存储为装箱对象。
一般来说,如果您有一些自定义属性,则无需担心。但是,如果您有一个复杂的场景,其中有数千个自定义依赖项对象飞来飞去,您可能需要考虑装箱/拆箱性能优化。
The short answer is yes.
The underlining storage for dependency property values does not have a notion of value types and stores everything as object, which will cause boxing. The framework itself uses a 'clever trick' for Boolean properties storage optimization via a helper class BooleanBoxes, which has true and false values stored as boxed objects.
In general if you have a few custom properties you have nothing to worry about. However if you have a complex scene that has thousands of your custom dependency objects flying around you may want to think about boxing/unboxing performance optimizations.
除了其他答案之外:
当 WPF 读取或更改依赖项属性(绑定和动画)时,它不会使用这些 setter 和 getter。因此,您在代码中显示的(取消)装箱将不会被执行。
您展示的这些 setter 和 getter 是为我们开发人员准备的。
In addition to the other answers:
When WPF reads or changes a dependency property (binding and animation) it does NOT use these setters and getters. So the (un)boxing you are showing in the code will not be executed.
These setters and getters you are showing are for us, developers.
它可能会使用拳击,但由于这是用户缩放的,因此不会出现问题。
请注意,通常也会涉及转换器。
It will probably use boxing, but as this is user-scaled it shouldn't happen on a scale that would be a problem.
Note that quite often a Convertor will be involved too.