40 向下转换 as 定义接口
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 向下转换 { class Program { //基类向派生类转换成为向下转换 //用is关键字进行检查, //向下转换如想使用派生类的方法需要进行强制转换 static void Main(string[] args) { B b = new B(); A a = b; // a.WordB();//此处报错 a.Word1(); if (a is B) { B b1 = (B)a; b1.WordB(); } } } class A { public void WordA() { Console.WriteLine("A1"); } public virtual void Word1() { Console.WriteLine("A"); } } class B:A { public void WordB() { Console.WriteLine("B1"); } public override void Word1() { Console.WriteLine("B1"); } } }
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 向下转换 { class Program { //基类向派生类转换成为向下转换 //用is关键字进行检查, //向下转换如想使用派生类的方法需要进行强制转换 static void Main(string[] args) { B b = new B(); A a = b; // a.WordB();//此处报错 a.Word1(); if (a is B) { B b1 = (B)a; b1.WordB(); } } } class A { public void WordA() { Console.WriteLine("A1"); } public virtual void Word1() { Console.WriteLine("A"); } } class B:A { public void WordB() { Console.WriteLine("B1"); } public override void Word1() { Console.WriteLine("B1"); } } }
接口:用关键字,interface声明 接口的方法和属性不用加public即使加也会报错。
接口的引用符可以指向多个对象这样就实现了接口的多态。
View Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 接口 { class Program { static void Main(string[] args) { IBankAccount account = new Bank(); account.cunkuan(1000); account.qukuan(500); Console.WriteLine("余额为{0}",account.Blance); } } class Bank:IBankAccount { private decimal blance; public decimal Blance { get { return blance; } } public void cunkuan(decimal amount) { blance += amount; } public bool qukuan(decimal amount) { if (blance >= amount) { blance -= amount; return true; } else { Console.WriteLine("余额不足,取款失败"); return false; } } } }

浙公网安备 33010602011771号