“Interface not implemented” when Returning Derived Type

前端 未结 12 819
野趣味
野趣味 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:52

    For what you want to do you'll probably want to implement the interface explicitly with a class (not interface) member that returns the List instead of IEnumerable...

    public class MyData : ISomeData
    {
        private List m_MyData = new List();
        public List Data
        {
            get
            {
                return m_MyData;
            }
        }
    
        #region ISomeData Members
    
        IEnumerable ISomeData.Data
        {
            get
            {
                return Data.AsEnumerable();
            }
        }
    
        #endregion
    }
    

    Edit: For clarification, this lets the MyData class return a List when it is being treated as an instance of MyData; while still allowing it to return an instance of IEnumerable when being treated as an instance of ISomeData.

提交回复
热议问题