Why Dependency property are declared as static readonly?

后端 未结 3 2136
傲寒
傲寒 2021-02-20 09:41

It is clear to me why dependency property are static and the question still remain on my mind is why we need to use Readonly keyword at the time of declaration of Dependency Pro

相关标签:
3条回答
  • 2021-02-20 09:50

    Conceptually a dependency property is something that a dependency object simply has and that does not depend on when you use the property. Just like a CLR property, if you ask does this object have a Total property, you know it cannot be a double now but an int later. As a result, we'd make the dependency property const if we could, but we cannot, so readonly is the next best thing.

    Using the readonly keyword has at least three effects:

    • it informs readers of the code that the value will not change
    • it prevents the author from accidentally changing the value
    • it assists the compiler, which benefits from knowing when things will not change
    0 讨论(0)
  • 2021-02-20 09:59

    Hopefully this would help: Silverlight.net forums: DependencyProperty - public static readonly?

    To quote:

    The "public static readonly" is the field that comes back from the Register call. The field is the identifier for the property. You only really need the identifier so that the Silverlight property system knows what to do, and so that you can use the property system yourself as you define the dependency property's CLR "wrapper". Once you have the wrapper, all further usage of the property can just use it like a typical property.

    Public so that all property system calls including cross-assembly can access it.

    Static and readonly because this isn't a definition that should ever change; the property system needs to get consistent results.

    In the attached property case, you want there to be an "owner" class. The owner class must be the class that calls RegisterAttached, AND must also define the static accessor methods (Get* and Set*) so that the XAML parser knows what to do when you try to set the attached property on a DependencyObject instance. So it's a little different, because for an attached property there usually isn't a "wrapper", any code access just uses the Get* and Set* accessors.

    0 讨论(0)
  • 2021-02-20 10:09

    Because it makes it obvious, that the value of this property cannot be changed after initialization.

    0 讨论(0)
提交回复
热议问题