“Interface not implemented” when Returning Derived Type

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

The following code:

public interface ISomeData
{
    IEnumerable Data { get; }
}

public class MyData : ISomeData
{
    private List

        
12条回答
  •  广开言路
    2020-11-27 21:46

    If you need to have a list in your interface (known number of items with random access), you should then consider changing the interface to

    public interface ISomeData
    {
        ICollection Data { get; } 
    }
    

    This will give you both the extensibility and the features you need from a list.

    List cannot be easily subclassed, meaning that you might have trouble returning that exact type from all the classes that want to implement your interface.

    ICollection on the other hand, can be implemented in various ways.

提交回复
热议问题