2009-06-10 19 views
1

我公司擁有一批多項目班,每個有奇異項類的集合,像這樣:如何使用泛型將此方法放在父類中?

public class Contracts : Items 
{ 
     public List<Contract> _collection = new List<Contract>(); 
     public List<Contract> Collection 
     { 
      get 
      { 
       return _collection; 
      } 
     } 
} 

public class Customers: Items 
{ 
     public List<Customer> _collection = new List<Customer>(); 
     public List<Customer> Collection 
     { 
      get 
      { 
       return _collection; 
      } 
     } 
} 

public class Employees: Items 
{ 
     public List<Employee> _collection = new List<Employee>(); 
     public List<Employee> Collection 
     { 
      get 
      { 
       return _collection; 
      } 
     } 
} 

我能想象我可以使用泛型把這個成父類。我怎麼能做到這一點,我想這將是這個樣子:

僞代碼:

public class Items 
{ 
     public List<T> _collection = new List<T>(); 
     public List<T> Collection 
     { 
      get 
      { 
       return _collection; 
      } 
     } 
} 

回答

6

這是完全正確的,但你也希望有一個<T>後的項目:

public class Items<T> 
{ 
     public List<T> _collection = new List<T>(); 
     public List<T> Collection 
     { 
      get 
      { 
       return _collection; 
      } 
     } 
} 

例化:

Items<Contract> contractItems = new Items<Contract>(); 
5

是的,雖然項目也必須是通用的。

public class Items<TItem> 
{ 
    private IList<TItem> _items = new List<TItem>(); 
    public IList<TItem> Collection 
    { 
     get { return _items; } 
    } 
    // ... 
} 

它很可能是有意義的有項目從IEnumerable<TItem>繼承了。

+0

如果從IEnumerable繼承的Items,那我會怎樣才能在foreach循環中使用Items?我正在尋找一種方法來做到這一點。 – 2009-06-10 12:59:32

相關問題