Why can't I use a compatible concrete type when implementing an interface

前端 未结 3 1086
深忆病人
深忆病人 2020-12-15 09:45

I would like to be able to do something like this :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
          


        
3条回答
  •  天命终不由人
    2020-12-15 10:01

    This is a Type Covariance/Contravariance issue (see http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#C.23 ).

    There's a workaround: use explicit interfaces, like so:

    public class Bar : IFoo {
    
        private IList _integers;
    
        IEnumerable IFoo.integers {
            get { return _integers };
            set { _integers = value as IList; }
        }
    
        public IList integers {
            get { return _integers; }
            set { _integers = vale; }
        }
    }
    

    Note that integers should be TitleCased to conform to .NET's guidelines.

    Hopefully you can see the problem in the code above: IList is compatible with IEnumerable only for the accessor, but not for setting. What happens if someone calls IFoo.integers = new Qux() (where Qux : IEnumerable but not Qux : IList).

提交回复
热议问题