2017-10-07 5 views
2

그 인터페이스를 구현 을 목록에 List<IInfrastructureEntity>. TestRepository (아래), I는 일반 TEntity을 복용하고에 , 클래스 유형을 결정하고 DataSource에서 해당 데이터를 가져 오십시오. 대신 각 return 문에서 다음과 같은 컴파일 타임 오류가 발생합니다. 어떤 TEntity도 반드시 IInfrastructureEntity을 구현하더라도. 변환 목록 <IInfrastructureEntity> 제네릭 형식 TEntity 반드시 내가 파일에서 요청 된 데이터를 가져 와서로서 돌려 정적 클래스 <code>DataSource</code>이

암시 내가 명시 적 변환을 어떻게해야합니까 'System.Collections.Generic.List<TEntity>'

에 유형 'System.Collections.Generic.List<IInfrastructureEntity>을'변환 할 수 없습니다?

public class TestRepository<TEntity> : IRepository<TEntity> where TEntity : IInfrastructureEntity 
{ 
    public List<TEntity> GetData() 
    { 
     TEntity checkType = default(TEntity); 
     if (checkType is Member) return DataSource.Members; 
     if (checkType is MenuItem) return DataSource.MenuItems; 
     if (checkType is CRAWApplication) return DataSource.CRAWApplications; 
     if (checkType is CRAWEntitlement) return DataSource.CRAWEntitlements; 
     if (checkType is FOXGroup) return DataSource.FOXGroups; 

     throw new NotSupportedException(checkType.ToString() + " is not yet supported"); 
    } 

    public List<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate) 
    { 
     return GetData().AsQueryable().Where(predicate); 
    } 

} 

답변

2

각 목록에서 수익을 명시 적 캐스트를 부과함으로써이 문제를 해결할 수 :

if (checkType is Member) return DataSource.Members.Cast<TEntity>().ToList(); 

문제는 반환 될 것으로 예상되는 유형 인 반면 DataSource.Members의 유형, List<IInfrastructureEntity> 때문이다 a List<TEntity>. 실제로 각 Entitywhere TEntity : IInfrastructureEntity으로 명시된대로 IInfrastructureEntity을 구현해야합니다. 그러나 유형이이 인터페이스를 구현한다고해도이 유형을 내재적으로 TEntity 오브젝트로 변환 할 수 있음을 의미하지는 않습니다. 이것이 명시 적 캐스트가 필요한 이유입니다.

+0

오우! 그게 그게 맞습니까? 고맙습니다. – Joe

+0

@Joe 오신 것을 환영합니다! 내가 도왔다 니 기쁘다. – Christos