IT

캐스트 목록

lottoking 2020. 8. 21. 08:06
반응형

캐스트 목록 목록에


public interface IDic
{
    int Id { get; set; }
    string Name { get; set; }
}
public class Client : IDic
{

}

어떻게 캐스트 List<Client>할 수 List<IDic>있습니까?


캐스팅 할 수 없습니다 (참조 ID 유지) - 안전하지 않습니다. 예를 들면 :

public interface IFruit {}

public class Apple : IFruit {}
public class Banana : IFruit {}

...

List<Apple> apples = new List<Apple>();
List<IFruit> fruit = apples; // Fortunately not allowed
fruit.Add(new Banana());

// Eek - it's a banana!
Apple apple = apples[0];

이제 공분산으로 인해 .NET 4 / C # 4에서 List<Apple>변환 할 수 있습니다. IEnumerable<IFruit>원하는 경우 목록 List<IFruit>을 선택 합니다. 예를 들면 :

// In .NET 4, using the covariance of IEnumerable<T>
List<IFruit> fruit = apples.ToList<IFruit>();

// In .NET 3.5
List<IFruit> fruit = apples.Cast<IFruit>().ToList();

그러나 이것은 원래 목록을 캐스팅하는 것과 동일하지 않습니다 . 이제 두 개의 존재 목록 이 있기 때문 입니다. 이것은 안전하지만 한 목록에 대한 변경 사항이 표시되지 않음 을 이해해야 합니다. ( 물론 목록이 참조 하는 개체 에 대한 수정 사항 이 표시됩니다.)


캐스트 반복기 및 .ToList () :

List<IDic> casted = input.Cast<IDic>().ToList() 트릭을 할 것입니다.

원래 저는 공분산이 효과가 있었지만 Jon이 지적 지적했듯이; 안돼!

그리고 원래 나도 멍청하게 ToList()전화를 받았어


나도이 문제를 사용 존 소총의 답변을 읽은 후 내가 사용하는 내 코드를 수정 List<T>사용 IEnumerable<T>. 이것이 OP의 원래 질문 인 I 캐스팅 수있는 방법 List<Client>에에List<IDic> , 대한 답변은 아니지만 그렇게 할 필요가 없으므로이 문제가 발생하는 다른 사람들에게 도움이 될 수 있습니다. 물론 이것은 사용이 필요한 코드가 List<IDic>귀하의 통제하에 있는 가정합니다 .

예 :

public void ProcessIDic(IEnumerable<IDic> sequence)
{
   // Implementation
}

대신에 :

public void ProcessIDic(List<IDic> list)
{
   // Implementation
}

LINQ를 사용할 수있는 권한을 부여 할 수 있습니다.

List<Client> clientList = new List<Client>();
List<IDic> list = clientList.Select(c => (IDic)c).ToList();

List<Client> listOfA = new List<Client>();
List<IDic> list = listOfA.Cast<IDic>().ToList();

새로 만들고 List<IDic>모든 요소를 전송할 수 있습니다.


.Net 3.5에서는 다음을 수행 할 수 있습니다.

List<ISomeInterface> interfaceList = new List<ISomeInterface>(list.Cast<ISomeInterface>());

이 경우 List 생성자는 IEnumerable을 사용합니다.
목록 은 IEnumerable로만 변환 할 수 있습니다. myObj 를 ISomeInterface로 변환 할 수 있지만 IEnumerable 유형은 IEnumerable로 변환 할 수 없습니다.

참고 URL : https://stackoverflow.com/questions/8925400/cast-listt-to-listinterface

반응형