zoukankan      html  css  js  c++  java
  • 显示接口成员

    如下面的IDrivable和IStreerable都声明了TurnLeft()方法

    public interface IDrivable

    {

      void TurnLeft();

    }

    public interface IStreerable

    {

      void TurnLeft();

    }

    如果声明一个类实现这两个接口,在类中必须定义两个TurnLeft()方法,如何区别这两个方法呢?答案是:必须显示声明这个方法属于哪个接口,如下例:

    1 /*
    2 Example8_7.cs illustrates an explicit interface member
    3 implementation
    4  */
    5
    6  using System;
    7
    8
    9 // define the IDrivable interface
    10 public interface IDrivable
    11 {
    12 void TurnLeft();
    13 }
    14
    15
    16 // define the ISteerable interface
    17 public interface ISteerable
    18 {
    19 void TurnLeft();
    20 }
    21
    22 // Car class implements the IMovable interface
    23 public class Car : IDrivable, ISteerable
    24 {
    25
    26 // explicitly implement the TurnLeft() method of the IDrivable interface
    27 void IDrivable.TurnLeft()
    28 {
    29 Console.WriteLine("IDrivable implementation of TurnLeft()");
    30 }
    31
    32 // implement the TurnLeft() method of the ISteerable interface
    33 public void TurnLeft()
    34 {
    35 Console.WriteLine("ISteerable implementation of TurnLeft()");
    36 }
    37
    38 }
    39
    40
    41 class Example8_7
    42 {
    43
    44 public static void Main()
    45 {
    46
    47 // create a Car object
    48 Car myCar = new Car();
    49
    50 // call myCar.TurnLeft()
    51 Console.WriteLine("Calling myCar.TurnLeft()");
    52 myCar.TurnLeft();
    53
    54 // cast myCar to IDrivable
    55 IDrivable myDrivable = myCar as IDrivable;
    56 Console.WriteLine("Calling myDrivable.TurnLeft()");
    57 myDrivable.TurnLeft();
    58
    59 // cast myCar to ISteerable
    60 ISteerable mySteerable = myCar as ISteerable;
    61 Console.WriteLine("Calling mySteerable.TurnLeft()");
    62 mySteerable.TurnLeft();
    63
    64 }
    65
    66 }
  • 相关阅读:
    Android Training
    Android Training
    简述Activity与Window关系
    简述Activity生命周期
    Python基础之元组及range
    python基础数据类型之列表
    python之字符串
    python基础之int整型
    python基础知识之格式化
    Python基础知识初识 (二)
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2037042.html
Copyright © 2011-2022 走看看