C#隐式实现接口成员与显示实现接口成员
2017-07-24 21:04
375 查看
C#在类中实现接口。实现接口的类必须包含该接口的所有成员的实现代码,且都是公共的。实现接口成员有隐式实现和显式实现两种方法。
隐式实现
如下图所示,类MyClass隐式地实现了接口IMyInterface的DoSomething和DoSomethingElse两个方法。对于隐式实现的成员,既可以通过类对象实例来访问,也可以通过接口来访问。如Main函数所示,两种调用方法都能成功。
namespace Ch10Ex03
{
class Program
{
public interface IMyInterface
{
void DoSomething();
void DoSomethingElse();
}
}
显式实现
如下图所示,类MyClass显式地实现了接口IMyInterface的DoSomething方法,隐式的实现了DoSomethingElse方法。对于显式实现的成员,只能通过接口来访问,不能使用类对象来访问。注意显式实现接口方法的时候不需要加public、private等关键词。
namespace Ch10Ex03
{
class Program
{
public interface IMyInterface
{
void DoSomething();
void DoSomethingElse();
}
}
隐式实现
如下图所示,类MyClass隐式地实现了接口IMyInterface的DoSomething和DoSomethingElse两个方法。对于隐式实现的成员,既可以通过类对象实例来访问,也可以通过接口来访问。如Main函数所示,两种调用方法都能成功。
namespace Ch10Ex03
{
class Program
{
public interface IMyInterface
{
void DoSomething();
void DoSomethingElse();
}
public class MyClass : IMyInterface { public void DoSomething() { Console.WriteLine("DoSomething\n"); } public void DoSomethingElse() { Console.WriteLine("DoSomethingElse\n"); } } static void Main(string[] args) { //通过类对象实例访问 MyClass myObj1 = new MyClass(); myObj1.DoSomething(); myObj1.DoSomethingElse(); //通过接口来访问 MyClass myObj2 = new MyClass(); IMyInterface myIntface = myObj2; myIntface.DoSomething(); myIntface.DoSomethingElse(); Console.ReadKey(); } }
}
显式实现
如下图所示,类MyClass显式地实现了接口IMyInterface的DoSomething方法,隐式的实现了DoSomethingElse方法。对于显式实现的成员,只能通过接口来访问,不能使用类对象来访问。注意显式实现接口方法的时候不需要加public、private等关键词。
namespace Ch10Ex03
{
class Program
{
public interface IMyInterface
{
void DoSomething();
void DoSomethingElse();
}
public class MyClass : IMyInterface { void IMyInterface.DoSomething() { Console.WriteLine("DoSomething\n"); } public void DoSomethingElse() { Console.WriteLine("DoSomethingElse\n"); } } static void Main(string[] args) { //通过接口来访问 MyClass myObj = new MyClass(); IMyInterface myIntface = myObj; myIntface.DoSomething(); myIntface.DoSomethingElse(); Console.ReadKey(); } }
}
相关文章推荐
- C#隐式实现接口成员与显示实现接口成员
- 小议C#接口的隐式与显示实现(续)
- C# 接口的隐式与显示实现
- C# 接口的隐式与显示实现
- 【转】C# 接口的隐式与显示实现
- C# 中 显示实现接口 与 隐式实现接口
- C# 接口的隐式与显示实现【转】
- C#隐式/显示实现接口方法详解
- C#中,接口的隐式实现和显示实现
- C# 接口的隐式与显示实现
- C# 接口的隐式与显示实现
- C# 接口的隐式与显示实现
- C# 接口的隐式与显示实现及适应场景
- c#显示实现接口和隐式实现的区别
- C# 接口的隐式与显示实现
- (原创)c#学习笔记10--定义类成员03--接口的实现01--显示实现接口成员
- C#接口的显示实现和隐式实现
- C# 接口的隐式与显示实现
- c# 接口的显示实现和隐式实现的区别