If a method returns an interface, what does it mean?

后端 未结 4 1375
眼角桃花
眼角桃花 2021-01-18 11:38

I see many methods that specify an interface as return value. Is my thought true that it means: my method can return every class type that inherits from that interface? if n

4条回答
  •  旧时难觅i
    2021-01-18 12:13

    Yes, your method could return any type that implements that interface.

    Here is an example:

    using System;
    
    class Foo
    {
        public IComparable GetComparable()
        {
            // Either of these return statements
            // would be valid since both System.Int32
            return 4;
            // and System.String
            return "4";
            // implement System.IComparable
        }
    }
    

提交回复
热议问题