2016-06-30 3 views
-1

하나의 공통 속성을 가진 여러 클래스가 있고 그 클래스의 생성자에서 해당 속성을 설정하고 있습니다.클래스 디자인 - 상속 또는 추상 또는 인터페이스

class Expense1 
{ 
    int _costval; 

    public Expense1(int cost) 
     { 
      _costval = cost; 
     } 

    ///other properties and methods.. 
} 
class Expense2 
{ 
    int _costval; 

    public Expense2(int cost) 
     { 
      _costval = cost; 
     } 

    ///other properties and methods... 
} 
class Expense3 
{ 
    public int _costval; 

    public Expense3(int cost) 
     { 
      _costval = cost; 
     } 

    ///other properties and methods... 
} 

어느 시점에서 "_costval"에 액세스해야합니다.

객체가 모든 유형의 expense1 또는 expense2 또는 expense3 될 수
Console.WriteLine(@object._costVal) 

같은 ..

내가 어떻게 할 수 있습니까? 기본 추상 클래스를 생성하고 costval 및 생성자를이 클래스로 옮겨야합니까? 조언을 부탁드립니다.

+4

내가 재산 단지 (가끔) 공공 필드 –

답변

1

인터페이스 또는 기본 클래스를 사용하여 동일한 결과를 얻을 수 있습니다. 그러나 인터페이스를 개발하면 느슨하게 결합되므로 더 나은 설계가 가능하며 brittle base class은 발생하지 않습니다. composition over inheritance

그래서 고향 :

public interface ICostable 
{ 
    int Cost { get; } 
} 

class Expense1 : ICostable 
{ 
    public int Cost { get; } 

    public Expense1(int cost) 
     { 
      Cost = cost; 
     } 

    ///other properties and methods.. 
} 

그런 다음 당신이 할 수 있습니다

public void PrintCost(ICostable item) 
{ 
    Console.WriteLine(item.Cost); 
} 
+0

메이크업 감각을 볼 수 없습니다. 감사 – bansi

관련 문제