曾英-C#教学-40 向下转换 as 定义接口安全
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _40_向上类型转换 { class Program { static void Main(string[] args) { B b = new B(); //这里通过转换之后并非彻底的类型转换 //这个步骤不能少 A a = b;//基类=派生类,这里派生类b赋值给基类a这里是向下类型的转换 //这里的a还不是彻底的转化成b类,但能够用b类中的虚方法 a.word();//这里的a类已是继承b类的了 //输出结果:B1,调用的是b类中的虚方法 /*--------------------------------------------------------------------*/ if (a is B)//这里并无彻底相等,可是这里是返回的true { B b1 = (B)a; //强制转换a,将具备基类与派生类属的a彻底转化换成B类 b1.wordB();//通过强制类型转换后的b1就能够调用B类中的方法了. } } } class A { public void wordA() { Console.WriteLine("A");} //基类虚方法 public virtual void word() { Console.WriteLine("A1"); } } //继承 class B : A { //定义了与类名相同的方法 public void wordB() { Console.WriteLine("B"); } //重写word虚方法,本身也是虚方法 public override void word() { Console.WriteLine("B1"); } } } //输出:B1
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _40_向上类型转换 { class Program { static void Main(string[] args) { B b = new B(); A a = b; B b1 = a as B;//a转化为B类的对象 //这是一个安全的转化 //这里若是不能转化,则返回值是空,若是能转化,则b1=a=new B(); if (b1 != null) b1.wordB(); //输出结果:B } } class A { public void wordA() { Console.WriteLine("A");} //基类虚方法 public virtual void word() { Console.WriteLine("A1"); } } //继承 class B : A { //定义了与类名相同的方法 public void wordB() { Console.WriteLine("B"); } //重写word虚方法,本身也是虚方法 public override void word() { Console.WriteLine("B1"); } } }
程序实例:ide
主函数: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _40_接口 { class Program { static void Main(string[] args) { //前面用到类,后面用到类的构造函数 //一个接口,多个方法的实现.多态的实现. IBankeAccount myAccount = new SaverAccount(); //接口的对象能够调用类中的普通方法,不须要强制转换. myAccount.PayIn(1000); //取钱 myAccount.WithShowMyself(200); Console.WriteLine("余额:" + myAccount.Balance); } } //银行帐户类 //这里要继承接口 //这里要使用并重写接口 class SaverAccount : IBankeAccount { private decimal balance; //存钱方法的重写 public void PayIn(decimal amount) {balance += amount;} //取钱的方法重写 public bool WithShowMyself(decimal amount) { //设立安全点 if (balance >= amount) { balance -= amount; return true; } else { Console.WriteLine("余额不足"); return false; } } //显示余额的属性重写 public decimal Balance { get { return balance;} } } } 接口定义: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _40_接口 { interface IBankeAccount { //存钱,接口中的方法没有用到public,可是永远都是公用的. void PayIn(decimal amount); //取钱,也没有用到方法体 bool WithShowMyself(decimal amount); //余额 decimal Balance { get; }//只读的属性 } }