zoukankan      html  css  js  c++  java
  • c#一个简单的实例告诉你,多继承还可以这么来

    我想多继承,要怎么搞???我想你一定会说“接口”,那么你有没有遇到这样的问题,你需要在一个类中继承另外2个类的所有方法,你要怎么做呢???难道要Coyp实现代码?No,往下看。。。

    定义一个空接口比如

    public interface I飞
    { }

    然后将你需要继承的一个类修改为静态的,然后修改方法。

    假如你的方法原来是这样的

      public  void 飞()
            {
                Console.WriteLine("开始飞了");
               
            }

    那么就修改为这样

    public static void 飞<T>(this T 飞实例) where T : I飞
    {
    Console.WriteLine("开始飞了");
    
    }

    然后你就可以继承了

      public class 苍蝇 : I飞
        {
            public virtual void 自我介绍()
            {
                Console.WriteLine("我是苍蝇");
            }
    
            public void 飞一个看看()
            {
                this.飞();           
            }
        }

    这样你就不需要为继承接口Copy相同的代码了

    全部代码:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace testjiekou
     7 {
     8     class Program
     9     {
    10         static void Main(string[] args)
    11         {
    12             超级老虎 t = new 超级老虎();
    13             t.自我介绍();
    14             t.我会飞()
    15             Console.ReadKey();
    16         }
    17     }
    18 
    19     public interface I飞
    20     { }
    21     public static class 飞接口的扩展
    22     {
    23         public static void 飞<T>(this T 飞实例) where T : I飞
    24         {
    25             Console.WriteLine("开始飞了");
    26         }
    27     }
    28 
    29     public class 老虎
    30     {
    31         public virtual void 自我介绍()
    32         {
    33             Console.WriteLine("我是老虎");
    34         }
    35     }
    36 
    37     public class 苍蝇 : I飞
    38     {
    39         public virtual void 自我介绍()
    40         {
    41             Console.WriteLine("我是苍蝇");
    42         }
    43 
    44         public void 飞一个看看()
    45         {
    46             this.飞();
    47         }
    48     }
    49 
    50     public class 超级老虎 : 老虎, I飞
    51     {
    52         public override void 自我介绍()
    53         {
    54             Console.WriteLine("我是超级老虎");
    55         }
    56         public void 我会飞()
    57         {
    58             this.飞();
    59         }
    60     }
    61 }

    怎么样,是不是有所感觉了呢。。。是不是发现什么了呢。。。

  • 相关阅读:
    【NIPS 2018】完整论文下载链接
    【今日CV 视觉论文速览】30 Nov 2018
    【超好玩的在线AI项目】浏览器里玩AI------持续更新
    hdu 4035 Maze 概率DP
    hdu 4089 Activation 概率DP
    hdu 4405 Aeroplane chess 概率DP
    zoj 3329 One Person Game 概率DP
    poj 2096 Collecting Bugs 概率DP
    poj 3744 Scout YYF I
    2013 Multi-University Training Contest 5 Partition
  • 原文地址:https://www.cnblogs.com/bfyx/p/4765977.html
Copyright © 2011-2022 走看看