开发者

Why does FxCop treat protected as public?

Why does FxCop treat protected members as if they are public throwi开发者_JAVA技巧ng DoNotDeclareVisibleInstanceFields error? I'm pretty sure protected members is a valid code design.


It's telling you not to declare fields which are visible outside the class, i.e. not private. In this case it is correctly recognising the protected modifier as exposing the members outside the class, albeit only to derived types.


I'm not sure if that's what you meant, but in general protected members are part of a class' interface.

You don't want public member variables because they make your implementation inflexible. Protected member variables do the same since classes that inherit from yours will depend on them, thus making your implementation inflexible.

Asaf


It looks like the error you're getting is flagging your externally visible instance fields. The recommended practice here is to make this field private and expose it through an externally visible property (with a public or protected access modifier).

The MSDN page on the error gives a good example:

using System;
namespace DesignLibrary
{
   public class BadPublicInstanceFields
   {
      // Violates rule DoNotDeclareVisibleInstanceFields.
      public int instanceData = 32;
   }

   public class GoodPublicInstanceFields
   {
      private int instanceData = 32;

      public int InstanceData
      {
         get { return instanceData; }
         set { instanceData = value ; }
      }
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜