I crea开发者_运维问答ted a Method called GetStudentMarks()
. The return-type of this method is generic List<StudentMark>
.The code works well even when i replaced the List<StudentMark>
with generic IList<StudentMark>
. How can an interface replace a class while interface contain only the declarations?
An interface cannot replace a class. It's just a blueprint for a class that has some implementation that corresponds by the guidelines that are set by the interface. So, you mostly will have one interface and than 1 or multiple classes that have some implementation for that interface like so:
public interface IMyInterface{
IList<string> SomeList { get; }
}
public class MyClass : IMyInterface {
public IList<string> SomeList {
get {
return new List<string>(){ "a", "b" , "c" };
}
}
}
It doesn't matter if the return type is interface or a solid class. Since inside the method you're returning the full type, the type is casted to the declared return type before returning the actual data so everything works as expected.
public IList<string> MyStrings()
{
return new List<string>(); // Cast happens here just before return (List -> IList)
}
Later if you require, you can cast the return type (IList) back to the solid class (List) and use it that way.
Interface
can not replace the Class
. Interface
can create an abstraction layer that hides actual object implementation beyound interface (that's why it's called interface).
Look on Polymorphism for explanation.
精彩评论