2016-06-30 40 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”。像

Console.WriteLine(@object._costVal) 

该对象可以是任何类型expense1或expense2或expense3的..

我该怎么办呢?我应该创建基本的抽象类并将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