C # 클래스에서 인터페이스로 변환 할 수 없음 [중복]

Dec 14 2020

나는 인터페이스를 처음 사용했지만 그것에 대해 읽은 후 인터페이스의 아이디어는 인터페이스에서 파생 된 클래스가 인터페이스가 허용되는 모든 곳에서 허용된다는 것이라고 생각했습니다. 내 코드는 다음과 같습니다.

public interface IPersonOfInterest
{ 
    //code requiring certain info to exist
}    
public abstract class PersonOfInterest
{
    public string[] GetBigPersonsInfo(List<IPersonOfInterest> FromList)
    {
        //code to gather a list of info that is guaranteed to be in any IPersonOfInterest
        return new string[] { };
    }
}

public class BigDonors : PersonOfInterest, IPersonOfInterest
{
    public List<BigDonors> SuchDonors = new List<BigDonors>();
    public void GimmeDemInfos()
    {
        string[] GetInfo = GetBigPersonsInfo(SuchDonors); //<-- compiler error here
    }
}

보시다시피 BigDonors, IPersonOfInterest인터페이스 에서 파생 됩니다. 그렇다면 왜 목록 BigDonor을 목록으로 변환 할 수 없다는 컴파일러 오류가 발생 IPersonOfInterest합니까? 나는 그들이 같은 것이 아니라는 것을 이해합니다. 여기서 뭘하려고하는지 알 것 같지만 그렇게하도록 놔두지는 않습니다.

편집 : 내 질문은 이미 답변으로 빠르게 표시되었지만 제공된 답변은 문제를 설명하지만 실제로 해결책을 제공하지는 않습니다. 그래서 내 솔루션 으로이 질문을 편집하고 있습니다.

저의 특별한 경우에는 적어도 추상적 인 방법이 아닌 목록에 기부자를 추가 할 필요가 없습니다. 그래서 Andrew Shepherd의 링크는 제 수업이 인터페이스로 변환 될 수는 있지만 목록은 불가능하다는 것이 문제라는 것을 보여주었습니다. 이제 컴파일러가 허용하는 읽기 전용 목록을 전달하고 있습니다.

public interface IPersonOfInterest
{ 
    //code requiring certain info to exist
}    
public virtual class PersonOfInterest : IPersonOfInterest
{
    //Changed to IReadOnlyList<IPersonOfInterest>, instead of List<IPersonOfInterest>:
    public string[] GetBigPersonsInfo(IReadOnlyList<IPersonOfInterest> FromList)
    {
        return new string[] { };
    }
}

public class BigDonors : PersonOfInterest
{
    public List<BigDonor> SuchDonors = new List<BigDonor>();    
    public void GimmeDemInfos()
    {
        //Added .AsReadOnly(), and it now compiles:
        string[] GetInfo = GetBigPersonsInfo(SuchDonors.AsReadOnly());
    }
}

답변

LajosArpad Dec 14 2020 at 07:08

인터페이스의 목적을 올바르게 식별했습니다. List<IPersonOfInterest>설명을 준수하므로을 사용해야 합니다.

간단히 말해서

BigDonor은 상속 IPersonOfInterest되었지만 List<BigDonor>에서 상속되지 않았습니다 List<IPersonOfInterest>. 즉 List<IPersonOfInterest>, 통과 해야 하지만 BigDonor해당 목록 에 요소를 추가 할 수 있습니다 .