zoukankan      html  css  js  c++  java
  • 强制转换对象为接口

    可用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 }
  • 相关阅读:
    雨林木风操作系统有感
    Bitcoin P2P 虚拟货币原理详解
    SVN switch 用法详解
    Bitcoin P2P 货币:有史以来最危险的项目
    回旋线科普
    Mathematica 如何绘制双纵坐标轴的图像?
    c#数据库操作
    在自定义HttpHandler中无法使用Session
    VS2010安装因net framework4.0无法安装而失败的解决方法
    .net framework 4.0 0xc8000247错误解决
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2037030.html
Copyright © 2011-2022 走看看