开发者

In WPF do DependencyProperty's cause lots of boxing/unboxing when used with value types?

开发者 https://www.devze.com 2023-03-24 04:48 出处:网络
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?

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 s开发者_开发技巧tatic readonly DependencyProperty PriceProperty =
        DependencyProperty.Register("Price", typeof(double), typeof(Quote), new UIPropertyMetadata(0.0d));


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消