简体   繁体   中英

Having trouble in C# Interfaces

I'm trying to understand the -why- of this ... and I'm really struggling to grasp the concept of what I'm telling the compiler to do when I use an IInterface syntax. Can anyone explain it in a "this is what's going on" way?

Anyway ... my main question is....

What is the difference between

public IEnumerable<string> MyMethod() {...}

and

public string MyMethod() : IEnumerable {...}

Why would you use one over the other?

public string MyMethod() : IEnumerable {...}

Will not compile, that's one difference.

But you could have

public class MyClass : IEnumerable<string> {...}

And then

public IEnumerable<string> MyMethod() 
{
   MyClass mc = new MyClass();
   return mc;
}

When you say public IEnumerable<string> MyMethod() {...} , you are declaring a method which returns some instance that implements IEnumerable<string> . This instance might be an array of string, a List<string> , or some type that you make.

When you say public class MyClass : IEnumerable<string> {...} , you are declaring a type which implements IEnumerable<string> . An instance of MyClass could be returned by MyMethod.

the first is a valid method declaration, as long as it is living in a Class ie

class MyClass 
{
    public IEnumerable<string> MyMethod() {...}
}

the second is not valid C# and will not compile. It is close to a Class declaration, tho.

class MyClass : IEnumerable<string>
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM