简体   繁体   English

接口如何替换类?

[英]How an interface can replace a class?

I created a Method called GetStudentMarks() . 我创建了一个名为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> . 此方法的返回类型为通用List<StudentMark> 。即使我将List<StudentMark>替换为通用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. 稍后,如果需要,可以将返回类型(IList)强制转换回实体类(List)并以这种方式使用。

Interface can not replace the Class . Interface不能代替Class Interface can create an abstraction layer that hides actual object implementation beyound interface (that's why it's called interface ). Interface可以创建一个抽象层 ,以隐藏实际的对象实现beyound接口(这就是为什么将其称为interface )。 Look on Polymorphism for explanation. 查看多态性以获取解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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