A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 翁金鹏 中级黑马   /  2012-4-11 07:55  /  1831 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

如题

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

1 个回复

倒序浏览
C# 中的接口与类不同,可以使用多继承,即一个子接口可以有多个父接口。但如果两个父成员具有同名的成员,就产生了二义性(这也正是 C# 中类取消了多继承的原因之一),这时在实现时最好使用显式的声明

示例:

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

namespace Example17
{
    class Program
     {
        //一个完整的接口声明示例
        interface IExample
         {
            //属性
            string P
             {
                 get;
                 set;
             }
            //方法
            string F(int Value);
            //事件
            event EventHandler E;
            //索引指示器
            string this[int Index]
             {
                 get;
                 set;
             }
         }
        interface IA
         {
            int Count { get; set;}
         }
        interface IB
         {
            int Count();
         }
        //IC接口从IA和IB多重继承
        interface IC : IA, IB
         {
         }
        class C : IC
         {
            private int count = 100;
            //显式声明实现IA接口中的Count属性
            int IA.Count
             {
                 get { return 100; }
                 set { count = value; }
             }
            //显式声明实现IB接口中的Count方法
            int IB.Count()
             {
                return count * count;
             }
         }
        static void Main(string[] args)
         {
             C tmpObj = new C();

            //调用时也要显式转换
             Console.WriteLine("Count property: {0}", ((IA)tmpObj).Count);
             Console.WriteLine("Count function: {0}", ((IB)tmpObj).Count());

             Console.ReadLine();
         }
     }
}

结果:
Count property: 100
Count function: 10000

评分

参与人数 1技术分 +2 收起 理由
宋天琪 + 2

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马