什么是使用界面的优势在哪里? [英] What is the advantage of using Interface?

查看:108
本文介绍了什么是使用界面的优势在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么用使用界面?

我听说,这是用来代替多重继承和数据隐藏,也可以用它做。

I heard that it is used instead of multiple inheritance and data-hiding can also be done with it.

有没有其他的优势,哪里有地方接口使用,以及如何能程序员识别接口是必要的?

Is there any other advantage, where are the places interface is used, and how can a programmer identify that interface is needed?

显式接口实现隐式接口实现

推荐答案

要解决隐性/显性的问题,比方说,两个不同的接口有相同的声明:

To tackle the implicit/explicit question, let's say that two different interfaces have the same declaration:

interface IBiographicalData

    {
       string LastName
       {
          get;
          set;
       }

    }

    interface ICustomReportData
    {
       string LastName
       {
          get;
          set;
       }
    }

和你有一个类实现两个接口:

And you have a class implementing both interfaces:

class Person : IBiographicalData, ICustomReportData
{
    private string lastName;

    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
}

类Person的的同时实现了接口,因为你得到了相同的输出与以下code:

Class Person Implicitly implements both interface because you get the same output with the following code:

Person p = new p();
IBiographicalData iBio = (IBiographicalData)p;
ICustomReportData iCr = (ICustomReportData)p;

Console.WriteLine(p.LastName);
Console.WriteLine(iBio.LastName);
Console.WriteLine(iCr.LastName);

不过,要的明确的实施,可以修改人,像这样的类:

However, to explicitly implement, you can modify the Person class like so:

class Person : IBiographicalData, ICustomReportData
{
    private string lastName;

    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }

    public string ICustomReportData.LastName
    {
        get { return "Last Name:" + lastName; }
        set { lastName = value; }
    }
}

现在的code:

Console.WriteLine(iCr.LastName);

是pfixed其中$ p $姓。

Will be prefixed with "Last Name:".

<一个href="http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx" rel="nofollow">http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx

这篇关于什么是使用界面的优势在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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