加入收藏 | 设为首页 | 会员中心 | 我要投稿 徐州站长网 (https://www.0516zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > 网站设计 > 教程 > 正文

显示实现接口成员

发布时间:2016-11-04 22:47:07 所属栏目:教程 来源:站长网
导读:using System; using System.Collections.Generic; using System.Linq; using System.Text; #region/*试想一下,如果在一个类A继承自接口B和C,并且在B和C中包含具有相同签名的成员,那么在类中实现该成员将导致两个接口都使用该成员作为他们的实现,然而

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

#region
/*试想一下,如果在一个类A继承自接口B和C,
并且在B和C中包含具有相同签名的成员,
那么在类中实现该成员将导致两个接口都使用该成员作为他们的实现,
然而,如果两个接口成员实现不同的功能,
那么将会导致一个接口的成员实现不正确或两个接口的成员实现都不正确,
这个时候我们应该如何处理呢?我们可以显示的实现接口成员,
即创建一个仅通过接口调用并且特定于该接口的类成员。*/
#endregion
namespace 显示实现接口成员
{
    interface ImyInterface1
    {
        int Add();
    }
    interface ImyInterface2
    {
        int Add();
    }
    class myClass : ImyInterface1, ImyInterface2 
    {
        int ImyInterface1.Add()                     //显式接口成员实现
        {
            int x = 3;
            int y = 5;
            return x + y;
        }
        int ImyInterface2.Add()                      //显式接口成员实现
        {
            int x = 3;
            int y = 5;
            int z = 7;
            return x + y + z;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ImyInterface1 i1 = new myClass();//使用接口继承类的对象实例化接口
            Console.WriteLine(i1.Add());     //使用接口对象调用接口中方法
            ImyInterface2 i2 = new myClass();
            Console.WriteLine(i2.Add());
            Console.ReadKey();
        }
    }
}

(编辑:徐州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读