2016-08-12 1 views
0

ServerType 형식의 일반 BindingList를 반환하는 메서드를 상속하려고합니다. 예를 들어, 다음과 같은 I가 있다고 가정 해 봅시다 : 다른 일반 반환 형식을 사용하여 메서드를 상속하는 방법

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 방법이 단지는 바인딩 에 목록 변환된다

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; } } 

는 다음에서 상속이 하나를 사용하십시오. 이를 수행하기 위해 목록 에 대한 간단한 확장 메소드를 작성할 수 있습니다. 그것은 서버 클래스 또는 귀하의 코드에서 다른 것과 아무 상관이 없습니다. –

+0

구현에서 ToBindingList() 구현을 반복해야하는 것처럼 보이지 않습니다. 내가 놓친 게 있니? – dasblinkenlight

+0

BindingList가 필요한 다른 deived 클래스가 있습니다. 다른 저장소 유형. 그래서 BindingList ToBindingList()와 같은 것을 할 수 있어야합니다. – GhostHunterJim

답변

1

첫째, 모든 컬렉션에 대한 기본 목록을 만들 :

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

감사합니다! 이것은 효과가 있었다. foreach 루프를 약간 수정하고 "Repository"데이터 유형을 "T"로 대체했습니다. – 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을 가질 수 있습니다.

관련 문제