Method with same name and signature but different return type in C#

后端 未结 9 1771
南旧
南旧 2020-12-08 01:01

I had an interview where I was asked the following:

Question: A method with same name and signature but different return type. Is it possible and what is this type c

9条回答
  •  抹茶落季
    2020-12-08 01:40

    Though return type covariance is not supported in C#, it is possible to emulate it by using explicit implementation and method hiding. That is a pattern which is used thoroughly in the ADO.NET APIs.

    E.g.:

    public interface ISomeValue { }
    public abstract class SomeValueBase : ISomeValue { }
    public class SomeValueImpl : SomeValueBase { }
    
    public interface ISomeObject { ISomeValue GetValue(); }
    
    public abstract class SomeObjectBase : ISomeObject
    {
        ISomeValue ISomeObject.GetValue() { return GetValue(); }
        public SomeValueBase GetValue() { return GetValueImpl(); }
    
        protected abstract SomeValueBase GetValueImpl();
    }
    
    public class SomeObjectImpl : SomeObjectBase
    {
        protected override SomeValueBase GetValueImpl() { return GetValue(); }
        public new SomeValueImpl GetValue() { return null; }
    }
    

    By doing that, the net result of calling GetValue() is that it will always match the most specific available type.

提交回复
热议问题