为什么要有“显示实现接口”?
•可以解决重名方法的问题。
什么是“显示实现接口”?
•实现接口中的方法时用:接口名.方法名(),并且没有访问修饰符,private
显示实现接口”后怎么调用?
•只能通过接口变量来调用,因为显示实现接口默认为private。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _02显示实现接口
{
class Program
{
static void Main(string[] args)
{
//IFlyable fly = new Student();
//fly.Fly();
//ISupperMan man = new Student();
//man.Fly();
//Student student = new Student();
////这里调用的结果是IFlyable接口中的Fly方法。
////因为显示实现接口后,被实现的方法变成了private的。所以通过类对象访问不到。
////这里由于Student类,实现两个接口的时候,都是通过“显示实现接口”来实现的,所以对于Student类来说,这些实现接口的方法都是"私有"的,所以通过Student对象都无法访问。
////student.Fly();
//Console.ReadKey();
Chinese cn = new Chinese();
Console.WriteLine(cn[3]);
Console.ReadKey();
//ISupperMan fly = new MyClass();
//fly.Fly();
//Console.ReadKey();
//接口不能被实例化。
//IFlyable fly = new IFlyable();
}
}
public interface IFlyable
{
void Fly();
string Name
{
get;
set;
}
string this[int index]
{
get;
set;
}
}
public interface ISupperMan
{
void Fly();
}
public class Chinese
{
//public string Item
//{
// get;
// set;
//}
private string[] names = new string[] { "乔丹", "科比", "韦德", "赵晓虎" };
public string this[int index]
{
get
{
return names[index];
}
set
{
names[index] = value;
}
}
}
public abstract class Teacher : IFlyable
{
#region IFlyable 成员
//子类,可以在实现接口的时候把接口中的方法实现为virtual的或者是abstract的,都可以。
public abstract void Fly();
#endregion
#region IFlyable 成员
public string Name
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string this[int index]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
}
public class Student : ISupperMan, IFlyable
{
//类中的成员如果不写访问修饰符则默认为private.
//类如果不写访问修饰符默认是internal
#region ISupperMan 成员
//显示实现接口目的:为了解决方法重名的问题。
void ISupperMan.Fly()
{
Console.WriteLine("ISupperMan接口中的Fly方法。(显示实现的接口)");
}
#endregion
#region IFlyable 成员
//public void Fly()
//{
// Console.WriteLine("IFlyable接口中的Fly方法.");
//}
#endregion
#region IFlyable 成员
void IFlyable.Fly()
{
Console.WriteLine("IFlyable中的Fly方法。");
}
#endregion
}
// 不报错,但是这是无法区分是哪个接口的Fly方法。
public class MyClass : ISupperMan, IFlyable
{
public void Fly()
{
Console.WriteLine("Fly...");
}
}
}