为什么我们应该实现接口? [英] Why we should implement Interface?

查看:147
本文介绍了为什么我们应该实现接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现接口只提供方法的框架。如果我们知道该方法的确切签名行,在这种情况下为
实现接口的要求是什么?

这是实现接口的情况

Implementing Interface just provide the skeleton of the method. If we know the exact signature line of that method, in this case
what is the requirement to implement Interface?
This is the case in which Interface has been implemented

interface IMy
{
    void X();
}
public class My:IMy
{
    public void X()
    {
        Console.WriteLine("Interface is implemented");
    }
}

这是Interface尚未实现的情况

This is the case in which Interface has not been implemented

public class My
{
    public void X()
    {
        Console.WriteLine("No Interface is implemented ");
    }
}


My obj = new My();
obj.X();

两种方法都会产生相同的结果。

实现接口的要求是什么?

Both the approaches will produce the same result.
what is the requirement to implement Interface?

推荐答案

有两个目的: .net中的继承:

There are two purposes of inheritance in .net:


  1. 允许派生类共享通用功能的基类实现
  2. 允许派生 - 在接受后者的任何地方替换基类对象的类对象。
  1. Allow derived classes to share the base-class implementations of common functionality
  2. Allow derived-class objects to be substituted for base-class objects anywhere the latter would be accepted.

与某些允许多重继承的语言(例如C ++)不同,.net要求每个类都有一个父类型(Object,如果没有别的话) )。另一方面,有时候让一个类可以替代许多不相关的类型是有用的。这就是接口的用武之地。

Unlike some languages (C++, for example) which allow multiple inheritance, .net requires every class to have precisely one parent type (Object, if nothing else). On the other hand, sometimes it's useful to have a class be substitutable for a number of unrelated types. That's where interfaces come in.

实现接口的对象可以替代该声明的接口类型的实例。即使对象只能从一种基类型继承,它们也可以实现任意数量的接口。因此,这允许多重继承的一些功能,而没有完全多重继承支持的复杂性和缺点。

An object which implements an interface is substitutable for an instance of that declared interface type. Even though objects may only inherit from one base type, they may implement an arbitrary number of interfaces. This thus allows some of the power of multiple inheritance, without the complications and drawbacks of full multiple-inheritance support.

这篇关于为什么我们应该实现接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆