2016-08-12 69 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。

相关问题