C#之类继承,接口学习案例
2016-09-03 09:30
411 查看
using System; using System.Collections.Generic; using System.Linq; using System.Text; //接口的声明案例 /*namespace Interface_test { interface Ifunction1 //接口1 { int sum(int i, int j); //只声明不实现 } interface Ifunction2 //接口2 { string str { get; set; } } class Test : Ifunction1, Ifunction2 //此处的冒号表示接口的实现 { private string Str; public Test() //构造函数 { } public Test(string str) { Str = str; } //实现接口Ifunction1的方法 public int sum(int i, int j) { return i + j; } //实现接口Ifunction 中的属性 public string str { get { return Str; } set { Str = value; } } } class Program { static void Main() { //直接访问实例 Test A = new Test(); Console.WriteLine(A.sum(15,20)); Test B = new Test("hello world"); Console.WriteLine(B.str); //使用接口 Ifunction1 f1 = (Ifunction1)A; Console.WriteLine(f1.sum(25, 30)); Ifunction2 f2 = (Ifunction2)B; Console.WriteLine(f2.str); Console.ReadLine(); } } }*/ namespace InterfaceExample { class BClass1 //基类 { public int add(int i, int j) { return i + j; } } interface IBfunction //接口1 { int Multiply(int i, int j); } class BClass2 : IBfunction { public int Substract(int i, int j) { return i - j; } int IBfunction.Multiply(int i, int j) //实现接口 { return i * j; } } interface Ifunction1 { int add(int i, int j); //接口定义的方法 } interface Ifunction2 { int Substract(int i, int j); } //通过接口实现多继承 class MyClass : BClass2, Ifunction1, Ifunction2 { //实现接口Ifunction1中的方法 int Ifunction1.add(int i, int j) { BClass1 class1=new BClass1(); return class1.add(i,j); } //实现接口Ifunction2中的方法 int Ifunction2.Substract(int i, int j) { BClass2 class2 = new BClass2(); return class2.Substract(i,j); } //增加新的方法 public void hello() { Console.WriteLine("hello"); } } class Program { static void Main() { MyClass myClass = new MyClass(); Ifunction1 f1 = (Ifunction1)myClass; Console.WriteLine(f1.add(8, 3)); Ifunction2 f2 = (Ifunction2)myClass; Console.WriteLine(f2.Substract(8, 3)); IBfunction f3 = (IBfunction)myClass; Console.WriteLine(f3.Multiply(8, 3)); myClass.hello(); Console.ReadLine(); } } }
相关文章推荐
- C#与Java对比学习:类型判断、类与接口继承、代码规范与编码习惯、常量定义
- C#与Java对比学习:类型判断、类与接口继承、代码规范与编码习惯、常量定义
- C#与Java对比学习:类型判断、类与接口继承、代码规范与编码习惯、常量定义
- c#学习摘录:类\继承\接口\字段、方法、属性\浅深复制(3)
- C# 你什么让程序员寂寞成酱紫 (男生版 娱乐中学习 抽象类 接口 继承 实现方法 )
- c#学习摘录:类\继承\接口\字段、方法、属性\浅深复制(1)
- C#学习笔记(二):继承、接口和抽象类
- c#学习笔记之类接口
- C#与Java对比学习:类型判断、类与接口继承、代码规范与编码习惯、常量定义
- C#之类中new方法学习案例
- C#与Java对比学习:类型判断、类与接口继承、代码规范与编码习惯、常量定义
- c#学习摘录:类\继承\接口\字段、方法、属性\浅深复制(4)
- c#学习笔记五 面向对象编程的基本概念 接口 继承和多态
- C#与Java对比学习:类型判断、类与接口继承、代码规范与编码习惯、常量定义
- C#与Java对比学习:类型判断、类与接口继承、代码规范与编码习惯、常量定义
- C#与Java对比学习:类型判断、类与接口继承、代码规范与编码习惯、常量定义
- C#学习——继承接口多态
- C#学习1——继承和接口
- c#学习摘录:类\继承\接口\字段、方法、属性\浅深复制(2)
- C#学习笔记--类的重要特性:继承(转载)