C # - methods that return interfaces

I am a bit confused about the concept of methods that return interfaces. Is there an article or link that discusses this in detail? I am confused about when / why you can do this, and how to do it, that you can use the interface for / from the object associated with it (I think this is correct).

+3
source share
4 answers

I am confused when / why you can do this,

The return of the interface is good if you want to separate the contract from what something should do, from a specific implementation (how to do it). Having an interface allows you to reuse and change the code more easily.

IFoo SimpleFoo, IFoo , . AdvancedFoo, IFoo. , , - . , .

, . List<T>, IEnumerable<T>, . , " " (, ), .

/ ,

, . , , . . , , , .

, :

IFoo foo = getFoo();
SimpleFoo simpleFoo = (SimpleFoo)foo;

, , as:

IFoo foo = getFoo();
SimpleFoo simpleFoo = foo as SimpleFoo;
if (simpleFoo == null)
{
     // Too bad...
}
else
{
    // Now we can use simpleFoo.
}
+14

, , . , , , .

:

public interface IFooBar
{
    String GetData();
}

public class Foo : IFooBar
{
    public String GetData() { return "Foo"; }
}

public class Bar : IFooBar
{
    public String GetData() { return "Bar"; }
}

public class DataManager
{
    public static IFooBar GetFooBar()
    {
        IFooBar foobar = ...
        return foobar;
     }
}

public class MainAppClass
{
     public void SomeMethod()
     {
         //You don't care what type of class you get here
         //you only care that the object you get back let you
         //call GetData.
         IFooBar foobar = DataManager.GetFooBar();
         String data = foobar.GetData();
         //etc
     }
}
+1

, . , (). , .

, , , , . IEnumerable List, , . . , IEnumerable. .

0

. - , . , .

, . , :

using System.Collections.Generic;

ICollection<int> getCollection() {
    return new LinkedList<int>();
}

LinkedList, ICollection. , getCollection(), ICollection, LinkedList ICollection. LinkedList, , LinkedList, .

#

0

Source: https://habr.com/ru/post/1777200/


All Articles