C#高级(六)接口,接口继承

   接口我们在前面也已经有所提及。接口的命名传统上都以大写I 开头。

   我们假设这样一种情况,一个系统有很多用户,我们可以查询某个用户是否存在,并且可以修改用户的密码。但有可能某天我们的数据库从mysql 升级成为 sqlserver 。在这种情况下,我们看下面一个例子。

   

  1. using System;
  2. namespace gosoa.com.cn
  3. {
  4.     public interface IUserOperation
  5.     {
  6.         bool userExites(string username);
  7.          bool updateUserPwd(string newPwd,string oldPwd);
  8.     }
  9.     public class SqlUserOperation: IUserOperation
  10.     {
  11.         //这里我们假使 uname oldPwd 是通过sql在数据库中查到的。具体查询,这里就不说了。
  12.         string uname="pan";
  13.         public string oldPwd="gosoa.com.cn";
  14.         public bool userExites(string username)
  15.         {
  16.             if(username==uname)
  17.             {
  18.                 return true;
  19.             }else
  20.             {
  21.                 return false;
  22.             }
  23.         }
  24.          
  25.         public bool updateUserPwd(string newPwd,string oldPwd)
  26.         {
  27.             if(newPwd==oldPwd)
  28.             {
  29.                 return true;
  30.             }else
  31.             {
  32.                 return false;
  33.             }
  34.         }
  35.     }
  36.     
  37.     public class MainClass
  38.     {
  39.         static void Main(string [] args)
  40.         {
  41.             string   newPwd =Console.ReadLine();
  42.             string   username =Console.ReadLine();
  43.             SqlUserOperation one=new SqlUserOperation();
  44.             IUserOperation tow=new  SqlUserOperation();
  45.             if(tow.userExites(username))
  46.             {
  47.                   Console.WriteLine("用户存在");
  48.             }else
  49.             {
  50.                   Console.WriteLine("用户不存在");
  51.             }
  52.             if(tow.updateUserPwd(newPwd,one.oldPwd))
  53.             {
  54.                 Console.WriteLine("密码修改成功");
  55.             }else
  56.             {
  57.                 Console.WriteLine("密码修改失败");
  58.             }
  59.         }
  60.     }
  61.  
  62.     /*
  63.     //我们可能某天需要用mysql 数据库了。这时候的具体实现又有所不同了。
  64.     public class MysqlUserOperation: IUserOperation
  65.     {
  66.         
  67.     }
  68.     */
  69. }

注意,实现接口的类,必须实现类的全部成员。否则会报错喔。

   我们来看这一句IUserOperation tow=new  SqlUserOperation(); 该句把引用变量声明为IUserOperation的引用方式,这表示,他们可以指向实现这个接口的任何类的实例。

   同时,接口也可以彼此继承,但要注意,实现接口的类必须实现接口以及接口的父接口的所有方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值