2012-06-14 2 views
3

CA2104 (Do not declare readonly mutable reference types)에 대한 코드 분석 경고를 피하면서 종속성 속성을 구현하는 가장 좋은 방법은 무엇입니까 (또는 방법이 있습니까?). MSDN documentationDependencyProperty를 구현하는 가장 좋은 방법은 무엇이며 'CA2104 : 읽기 전용 변경 가능한 참조 유형을 선언하지 않습니까?'

은 종속성 속성을 선언하는이 방법 제안 :

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

을하지만 그 CA2104 발생합니다. 억압하기는 쉽지만, 더 좋은 방법이 있는지 궁금해했습니다.

답변

2

위양성입니다. DependencyProperty은 변경할 수 없습니다.

필드 대신 속성을 사용할 수 있지만 정적 생성자에서 설정해야 다른 경고가 트리거됩니다.

0

편집 : 더 자세히 살펴보면 이 경고는을 흡인합니다. CA2104의 전체적인 아이디어는 포인터를 잡고 그것을 사용하여 객체의 내용을 수정할 수 있다는 것입니다. 추가 속성에서 'Get'연산을 사용한다고해서 근본적인 문제가 해결되는 것은 아니며 코드 분석을 패턴을 받아들이는 것으로 바보 취급합니다. 이를 처리하는 적절한 방법은 Public 속성이있는 세상에서 DependencyProperty 클래스를 사용하는 것은 멍청한 경고이기 때문에 프로젝트의 속성에서 CA2104를 무시하는 것입니다.

이 경고는 DependencyProperties가 변경되지 않으므로 Metro에서는 유효하지 않은 것으로 보입니다. 그러나 DependencyProperty에 대한 쓰기 가능한 참조가있는 경우 소유자를 추가하거나 메타 데이터를 혼란시킬 수 있으므로 WPF에서는 유효합니다. 여기에 코드가 있는데 그것은 예쁘지 않지만 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); 
     } 
    }