接口的多继承会带来哪些问题
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
示例:
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
【接口的多继承会带来哪些问题】相关文章
2. 类、抽象类、接口的差异
4. 抽象类和接口的区别
10. 分布式数据库需要考虑哪些问题
本文来源:https://www.mianshiwenti.com/a12998.html
进入下载页面
上一篇:C#里面如何倒序排列一个数组的元素?
下一篇:武汉某公司的C#笔试题面试题
﹝接口的多继承会带来哪些问题﹞相关内容
- List, Set, Map是否继承自Collection接口?
- EJB需直接实现它的业务接口或Home接口吗,请简述理由
- remote接口和home接口主要作用
- 如果一个类实现了多个接口但是这些接口有相同的方法名将会怎样
- 介绍一下Ruby的多线程处理
- 跳槽思考 如何衡量跳槽带来的价值
- 你能为我们公司带来什么呢?
- 继承时候类的执行顺序问题,一般都是选择题,问你将会打印出什么?
- Java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请说出他们分别是哪些类
- Java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请说出他们分别是哪些类?