开发者

What's the best OOP pattern to do this in c# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 4 years ago.

Improve this question

The code snip开发者_开发技巧pet would not compile as it only meant to showcase what I would like to achieve: Say I have an Interface:

      public Interface IWalker 
      {
          //Compiles but not what I need
          double DistanceTravelled {get; set;}

          //Compiler error - cant be private for set, but that's what I need
          //double DistanceTravelled {get; private set;}
      }

      public abstract AbstractWalker : IWalker 
      {
           //Error:Cannot implement - but thats what I need
           //protected double DistanceTravelled {get; private set} 

           //Error the set is not public and I dont want the property to be public
           //public double DistanceTravelled { get;private  set; }

             //Compiles but not what i need at all since I want a protected 
             // property -a. and have it behave as readonly - b. but 
             // need it to be a part of the interface -c.
             public double DistanceTravlled {get; set;}

      }

All of my concrete instances of AbstractWalker are actually type of IWalker. What would be the best way to achieve the design I have specified in the snippet?


If you want private set, just specify a get in the interface:

  public interface IWalker 
  {
      double DistanceTravelled {get; }
  }

the implementer of IWalker can then specify private set:

  public class Walker : IWalker 
  {
      public double DistanceTravelled { get; private set;}
  }


There is a flaw in your design. An interface is used to describe the 'public contract' of your API, so it's very strange that you want (a) a private setter and (b) a protected implementation.

  • The private setter at the interface level does not make any sense (see Mark Heaths answer if you want a property with only a getter on the interface)
  • The protected implementation is also weird, since by implementing the interface the property is public anyway.

You will have to provide more information about your design if you need more help.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜