Left side interface

I know that we cannot create an instance Interface. but why can we write Interfaceon the left side? Are these links only an interface (for classes that implement this) instead of an instance?

If we cannot create an instance of the interface, what type is Pin this example?

string[] names = {"John", "Bob", "Mark"};
IEnumerable<string> P = names.Where(n => n.Contains('o'));
+3
source share
5 answers

P has type IEnumerable<string>

Here you declare the type of the local variable P.

Pcontains a type IEnumerable<string>, and although you do not instantiate the interface directly, you can create a specific class, but just keep a reference to the interface.

The instance returned here by the call Where()should only adhere to the contract that defines IEnumerable<string>.

+6

, , .

, - (p), , , , IEnumerable<string>.

, :

IBeast mrJuggles = new Tiger();

Mr.Juggles , IBeast. IBeast, , IBeast, IBeast.

+3

.

?

, : " -, ".

"-" - - .

, - , , ( - ..). . .

. -, - , .

:

using System.Collections.Generic;

namespace App
{
    class Program
    {
        class Example
        {
            List<string> list = new List<string> { "a", "b", "c" };

            public IEnumerable<string> AsEnumerable()
            {
                return list;
            }
        }

        static void Main(string[] args)
        {
            IEnumerable<string> foo = new Example().AsEnumerable();
            List<string> bar = (List<string>)foo;
        }
    }
}

, ?

IEnumerable<string> :

IEnumerable<string> foo = new Example().AsEnumerable();

: "foo - , IEnumerable".

-. IEnumerable , . IEnumerable - , .

List<string>, ? ( #, , Add Remove , . ).

: IEnumerable<string> , .

EDIT:

@Kjartan, :

bool isFooIEnumerable = foo is IEnumerable<string>; // it true 
bool isBarIEnumerable = bar is IEnumerable<string>; // true again
bool isFooList = foo is List<string>; // yup. true
bool isBarList = bar is List<string>; // true all the way
+2

.

IEnumerable<string> stringEnumerator

, stringEnumerator ​​ , .

,

IEnumerable<string> P = names.where(n => n.Contains('o'));

, p, IEnumerable<string> names.where(n => n.Contains('o'));

+1

, , , ( ) , .

P framework, IEnumerable<string>. ( Enumerable), (, , - ). , Microsoft , Where .NET. , , , , IEnumerable<string>, P , IEnumerable<string> .

0

All Articles