C# 接口不能完善的事


最近一直在想着一个问题,关于接口的问题,

先上代码吧,看完代码再看我想要问的问题吧,在求高手解释

 

 
  1. public interface IAnimal  
  2.     {  
  3.         /// <summary>  
  4.         /// 叫  
  5.         /// </summary>  
  6.         void Yell();  
  7.     }  
  8.   
  9.     public class Cat:IAnimal  
  10.     {  
  11.   
  12.         public void Yell()  
  13.         {  
  14.             System.Diagnostics.Debug.WriteLine("喵");  
  15.         }  
  16.   
  17.         public void Climb()  
  18.         {  
  19.             System.Diagnostics.Debug.WriteLine("我会爬树哦");  
  20.         }  
  21.     }  
  22.   
  23.     public class Dog : IAnimal  
  24.     {  
  25.   
  26.         public void Yell()  
  27.         {  
  28.             System.Diagnostics.Debug.WriteLine("汪");  
  29.         }  
  30.   
  31.     }  
  32.   
  33.     public class Test  
  34.     {  
  35.         public void DoSomething()  
  36.         {  
  37.             IAnimal cat = new Cat();  
  38.             cat.Yell();  
  39.             //cat.Climb(); //有时候,一个类里的一个方法,是它独有的,但希望在这里能用上,但接口上没这个方法  
  40.         }  
  41.     }  

 

有一个IAnimal的接口,它只有一个方法,就是Yell();

猫与狗都实现了这个接口,但猫还会爬树

然后,在使用的时候,也就是Test这个类中,一定要做Yell这个动作。

后来,我发现这个Test类中,需要用到猫的Climb这个动作,这时候,如何是好?

不能在IAnimal接口上加方法,因为它不是这个接口的一个标准,但也有一些实现的类要做这个动作。

那如何是好呢?

求解,求赐教


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM