更新:2007 年 11 月
| TypeName | PropertiesShouldNotBeWriteOnly | 
| CheckId | CA1044 | 
| 类别 | Microsoft.Design | 
| 是否重大更改 | 是 | 
原因
公共或受保护属性有 set 访问器,但是没有 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; 
         } 
      }
   }
}