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

后端 未结 9 1768
南旧
南旧 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

    In C#, you cannot have methods like

    int Foo() { return 1; }

    void Foo() { return; }

    They must vary by more than return type.

    If the arguments are different, then you're good to go.

    int Foo(string x) { return 1; }

    void Foo(double x) { return; }

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 01:43

    You can do it whit interface

       public interface IMyInterface
    {
        int Metoda1()enter code here`;
    }
    public class MyClass : test.IMyInterface
    {
        public IMyInterface Metoda1()
        {
            return new MyClas();
        }
        int test.IMyInterface.Metoda1()
        {
            return 1;
        }
    }
       static void Main(string[] args)
        {
            MyClass instance = new MyClass();
            IMyInterface inst = instance.Metoda1();
         /*   IMyInterface ints2 = inst.Metoda1(); //will not compile*/
            Console.WriteLine(inst.GetType().ToString()); ;
            object inst3 = inst.Metoda1();
            Console.WriteLine(inst3.GetType().ToString());
        }
    
    0 讨论(0)
提交回复
热议问题