• 强制转换对象为接口


    可用is运算符检查是否支持接口,用as运算符转换接口,如:

    1 /*
    2 Example8_4.cs illustrates casting an object
    3 to an interface
    4  */
    5
    6 using System;
    7
    8
    9 // define the IDrivable interface
    10 public interface IDrivable
    11 {
    12
    13 // method declarations
    14 void Start();
    15 void Stop();
    16
    17 // property declaration
    18 bool Started
    19 {
    20 get;
    21 }
    22
    23 }
    24
    25
    26 // Car class implements the IDrivable interface
    27 public class Car : IDrivable
    28 {
    29
    30 // declare the underlying field used by the Started property
    31 private bool started = false;
    32
    33 // implement the Start() method
    34 public void Start()
    35 {
    36 Console.WriteLine("car started");
    37 started = true;
    38 }
    39
    40 // implement the Stop() method
    41 public void Stop()
    42 {
    43 Console.WriteLine("car stopped");
    44 started = false;
    45 }
    46
    47 // implement the Started property
    48 public bool Started
    49 {
    50 get
    51 {
    52 return started;
    53 }
    54 }
    55
    56 }
    57
    58
    59 class Example8_4
    60 {
    61
    62 public static void Main()
    63 {
    64
    65 // create a Car object
    66 Car myCar = new Car();
    67
    68 // use the is operator to check that myCar supports the
    69 // IDrivable interface
    70 if (myCar is IDrivable)
    71 {
    72 Console.WriteLine("myCar supports IDrivable");
    73 }
    74
    75 // cast the Car object to IDrivable
    76 IDrivable myDrivable = (IDrivable) myCar;
    77
    78 // call myDrivable.Start()
    79 Console.WriteLine("Calling myDrivable.Start()");
    80 myDrivable.Start();
    81 Console.WriteLine("myDrivable.Started = " +
    82 myDrivable.Started);
    83
    84 // call myDrivable.Stop()
    85 Console.WriteLine("Calling myDrivable.Stop()");
    86 myDrivable.Stop();
    87 Console.WriteLine("myDrivable.Started = " +
    88 myDrivable.Started);
    89
    90 // cast the Car object to IDrivable using the as operator
    91 IDrivable myDrivable2 = myCar as IDrivable;
    92 if (myDrivable2 != null)
    93 {
    94 Console.WriteLine("Calling myDrivable2.Start()");
    95 myDrivable2.Start();
    96 Console.WriteLine("Calling myDrivable2.Stop()");
    97 myDrivable2.Stop();
    98 Console.WriteLine("myDrivable2.Started = " +
    99 myDrivable2.Started);
    100 }
    101
    102 }
    103
    104 }
  • 相关阅读:
    摩托罗拉SE4500 德州仪器TI Omap37xx/AM3715/DM3730/AM3530 wince6.0/Windows Mobile 6.5平台 二维软解调试记录及相关解释
    摩托罗拉SE4500 三星 S3C6410 Wince6.0平台软解码调试记录以及驱动相关问题解释
    MSM8909+Android5.1.1之系统烧录
    PIC16F914SEG脚中电路图注意事项
    PIC16F914ADC模块采集数据转换
    PIC914AD模块使用记录
    PIC914 LCDCON液晶控制寄存器用法
    PIC914SEG设置方法
    示波器用法
    检测单片机是否启动
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2037030.html
Copyright © 2020-2023  润新知