2016-08-12 73 views
0

我試圖繼承返回類型爲ServerType的泛型綁定列表的方法。舉例來說,假設我有以下幾點:如何繼承具有不同通用返回類型的方法

public interface IServer 
{ 

    string IpAddress { get; set; } 
    string Name { get; set; } 
    string HostName { get; set; } 
    string OsVersion { get; set; } 

} 

public class BaseServer : IServer 
{ 
    private string _IpAddress; 
    private string _Name; 
    private string _HostName; 
    private string _OsVersion; 

    public string IpAddress 
    { 
     get { return _IpAddress; } 
     set { _IpAddress = value; } 
    } 

    public string Name 
    { 
     get { return _Name; } 
     set { _Name = value; } 
    } 

    public string HostName 
    { 
     get { return _HostName; } 
     set { _HostName = value; } 
    } 

    public string OsVersion 
    { 
     get { return _OsVersion; } 
     set { _OsVersion = value; } 
    } 
} 

public class ServerTypeA : BaseServer { } 
public class ServerTypeB : BaseServer { } 
public class ServerTypeC : BaseServer { } 

public class ServerTypeList : List<ServerTypeA> 
{ 

    public BindingList<ServerTypeA> ToBindingList() 
    { 
     BindingList<ServerTypeA> myBindingList = new BindingList<ServerTypeA>(); 

     foreach (ServerTypeA item in this.ToList<ServerTypeA>()) 
     { 
      _bl.Add(item); 
     } 

     return _bl; 

    } 
} 

有什麼辦法,我可以做「ToBindingList」的方法,而不必重複它在每個派生服務器類,並將它使用正確的泛型類型。

+3

ToBindingList方法只是轉換列表到的BindingList 。你可以寫一個列表的簡單擴展方法來做到這一點。它與您的代碼中的Server類或其他任何內容無關。 –

+0

它看起來並不像你的實現需要重複'ToBindingList()'實現。我錯過了什麼嗎? – dasblinkenlight

+0

我有其他deived類,我需要一個BindingList。不同的存儲庫類型。所以我需要能夠做一些像BindingList ToBindingList() – GhostHunterJim

回答

1

首先,創建您的所有館藏基地名單:

public class MyListBase<T> : List<T> 
    where T: Server 
{ 
    public BindingList<T> ToBindingList() 
    { 
     BindingList<T> myBindingList = new BindingList<T>(); 
     foreach (T item in this.ToList<T>()) 
      myBindingList.Add(item); 
     return myBindingList; 
    } 
} 

然後用這個來繼承:

public class Repositories : MyListBase<Repository> 
{ 
} 
+0

謝謝!這工作。我對foreach循環做了一些修改,並用「T」取代了「Repository」數據類型。 – GhostHunterJim

+0

我的(複製粘貼)錯誤。我糾正了它。 –

2

先不從List<T>派生。相反使用它(favor composition over inheritance)。

然後讓你的Repositories -class通用:

public class Repository : Server 
{ 

} 

public class Repositories<T> where T: Server 
{ 

    private List<T> theList = new List<T>(); 

    public Repositories<T>(List<T> theList) this.theList = theList; } 

    public BindingList<T> ToBindingList() 
    { 
     BindingList<T> myBindingList = new BindingList<T>(); 

     foreach (Titem in this.theList) 
     { 
      _bl.Add(item); 
     } 

     return _bl; 

    } 
} 

現在你可以有任意類從Server派生的Repositories -instances。

相關問題