“Interface not implemented” when Returning Derived Type

前端 未结 12 851
野趣味
野趣味 2020-11-27 21:11

The following code:

public interface ISomeData
{
    IEnumerable Data { get; }
}

public class MyData : ISomeData
{
    private List

        
12条回答
  •  误落风尘
    2020-11-27 22:08

    What if you accessed your MyData object trough the ISomeData interface? In that case, IEnumerable could be of an underlying type not assignable to a List.

    IEnumerable iss = null;
    
    List ss = iss; //compiler error
    

    EDIT:

    I understand what you mean from your comments.

    Anyway, what I would do in your case would be:

        public interface ISomeData where T: IEnumerable
        {
            T Data { get; }
        }
    
        public class MyData : ISomeData>
        {
            private List m_MyData = new List();
            public List Data { get { return m_MyData; } }
        }
    

    Converting to generic Interface with appropriate constraint offers I think the best of both flexibility and readability.

提交回复
热议问题