C#多重继承 + 多态 + 扩展方法 简单示例

来源:互联网 发布:好的网络宣传方式 编辑:程序博客网 时间:2024/04/30 12:14
Code:
  1. public interface ITestA {   
  2.         /*  
  3.          * 不加下面这一句输出是  
  4.          * Test.TestA         
  5.          * ITestAHelper.TestA          
  6.          * 加上后输出是  
  7.          * Test.TestA  
  8.          * Test.TestA  
  9.             */  
  10.         //void TestA();   
  11.     }   
  12.     public static class ITestAHelper   
  13.     {   
  14.         public static void TestA(this ITestA obj)   
  15.         {   
  16.             Console.WriteLine("ITestAHelper.TestA");   
  17.         }   
  18.     }   
  19.     public interface ITestB { }   
  20.     public static class ITestBHelper   
  21.     {   
  22.         public static void TestB(this ITestB obj)   
  23.         {   
  24.             Console.WriteLine("ITestBHelper.TestB");   
  25.         }   
  26.     }   
  27.     public class Test : ITestA, ITestB   
  28.     {   
  29.         //此方法与ITestA的TestA()扩展方法相同   
  30.         public void TestA()   
  31.         {   
  32.             Console.WriteLine("Test.TestA");   
  33.         }   
  34.     }   
  35.     class Program   
  36.     {   
  37.         static void Main(string[] args)   
  38.         {   
  39.             Test obj1 = new Test();   
  40.             //下面分别测试2种TestA()调用方式   
  41.             obj1.TestA();   
  42.             ((ITestA)obj1).TestA();   
  43.             Console.ReadKey();   
  44.         }   
  45.     }  

 

原创粉丝点击