【问题标题】:What is the best way to implement a DependencyProperty and also avoid 'CA2104: Do not declare read only mutable reference types'?实现 DependencyProperty 并避免“CA2104:不要声明只读可变引用类型”的最佳方法是什么?
【发布时间】:2012-06-14 23:54:19
【问题描述】:

在避免CA2104 (Do not declare readonly mutable reference types) 的代码分析警告的同时实现依赖属性的最佳方法是什么(或者,有没有一种方法)?

MSDN documentation 建议以这种方式声明您的依赖属性:

  public static readonly DependencyProperty StateProperty = DependencyProperty.Register(
    "State", typeof(Boolean), typeof(MyStateControl),new PropertyMetadata(false));

但这会导致 CA2104。压制很容易,但我只是想知道是否有更好的方法。

【问题讨论】:

    标签: .net dependency-properties code-analysis fxcop


    【解决方案1】:

    这是误报; DependencyProperty 是不可变的。

    您可以使用属性而不是字段,但是您需要在静态构造函数中设置它,从而触发另一个警告。

    【讨论】:

      【解决方案2】:

      编辑:经过进一步思考,我认为这个警告很糟糕。 CA2104 的整个想法是您可以获取指针并使用它来修改对象的内容。对附加属性使用“获取”操作并不能解决根本问题,它只会欺骗代码分析以接受该模式。处理这个问题的正确方法是忽略项目属性中的 CA2104,因为在一个拥有公共 DependencyProperty 类的世界中,这是一个愚蠢的警告。

      此警告在 Metro 中似乎无效,因为 DependencyProperties 是不可变的。但是,它在 WPF 中似乎是有效的,因为如果您对 DependencyProperty 有可写引用,则可以添加所有者或弄乱元数据。这是代码,它不是很漂亮,但它通过了 FXCop 指南。

          /// <summary>
          /// Identifies the Format dependency property.
          /// </summary>
          private static readonly DependencyProperty labelPropertyField = DependencyProperty.Register(
              "Label",
              typeof(String),
              typeof(MetadataLabel),
              new PropertyMetadata(String.Empty));
      
          /// <summary>
          /// Gets the LabelProperty DependencyProperty.
          /// </summary>
          public static DependencyProperty LabelProperty
          {
              get
              {
                  return MetadataLabel.labelPropertyField;
              }
          }
      
          /// <summary>
          /// Gets or sets the format field used to display the <see cref="Guid"/>.
          /// </summary>
          public String Label
          {
              get
              {
                  return this.GetValue(MetadataLabel.labelPropertyField) as String;
              }
      
              set
              {
                  this.SetValue(MetadataLabel.labelPropertyField, value);
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-12
        • 1970-01-01
        • 2019-08-23
        • 2014-12-15
        • 1970-01-01
        • 2011-04-16
        相关资源
        最近更新 更多