共用方式為


屬性不應為唯寫

更新:2007 年 11 月

型別名稱

PropertiesShouldNotBeWriteOnly

CheckId

CA1044

分類

Microsoft.Design

中斷變更

中斷

原因

公用或保護的屬性具有 set 存取子 (Accessor),但沒有 get 存取子。

規則描述

Get 存取子會提供屬性的讀取權限,而 set 存取子則提供寫入權限。可接受並經常需要擁有唯讀屬性時,設計方針會禁止使用唯寫屬性,因為允許使用者設定值然後防止使用者檢視該值無法提供任何安全性的保護。同時,如果沒有讀取權限,則無法檢視共用物件的狀態,進而限制這些物件的使用性。

如何修正違規

若要修正此規則的違規情形,請將 get 存取子加入至屬性。此外,如果需要唯寫屬性行為,請考慮將這個屬性轉換為方法。

隱藏警告的時機

強烈建議您不要隱藏此規則的警告。

範例

在下列範例中,BadClassWithWriteOnlyProperty 是具有唯寫屬性的型別,GoodClassWithReadWriteProperty 則包含更正的程式碼。

Imports System

Namespace DesignLibrary

   Public Class BadClassWithWriteOnlyProperty

      Dim someName As String

      ' Violates rule PropertiesShouldNotBeWriteOnly.
      WriteOnly Property Name As String
         Set 
            someName = Value
         End Set 
      End Property

   End Class

   Public Class GoodClassWithReadWriteProperty

      Dim someName As String

      Property Name As String
         Get 
            Return someName
         End Get 

         Set 
            someName = Value
         End Set 
      End Property

   End Class

End Namespace
using System;

namespace DesignLibrary
{
   public class BadClassWithWriteOnlyProperty
   {
      string someName;

      // Violates rule PropertiesShouldNotBeWriteOnly.
      public string Name 
      { 
         set 
         { 
            someName = value; 
         } 
      }
   }

   public class GoodClassWithReadWriteProperty
   {
      string someName;

      public string Name 
      { 
         get 
         { 
            return someName; 
         } 
         set 
         { 
            someName = value; 
         } 
      }
   }
}