2010-11-25 29 views
1

的代碼片段將無法編譯,因爲它只是爲了展示我想實現什麼: 說我有一個接口:什麼是最好的面向對象模式在C#中做到這一點

 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;} 

     } 

我所有的混凝土AbstractWalker的實例實際上是IWalker的類型。 實現我在代碼片段中指定的設計的最佳方式是什麼?

+2

是否有某些原因需要成爲界面?抽象類基本上是一樣的,除了你可以添加受保護的方法。 – 2010-11-25 21:39:58

回答

10

如果你想私定,只是在界面中指定一個GET:

public interface IWalker 
    { 
     double DistanceTravelled {get; } 
    } 

IWalker的實施者可以再指定私定:

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

。在你的設計中的缺陷。一個接口被用來描述你的API的'公共契約',所以你很想要(a)一個私有的setter和(b)一個受保護的實現。

  • 在接口級別不作任何意義上的私人二傳手(見馬克荒地回答,如果你想,只有在接口上獲取方法的屬性)
  • 受保護的實現也奇怪,因爲通過實施無論如何,界面屬性是公共的。

如果您需要更多幫助,您將不得不提供有關您設計的更多信息。

相關問題