1 类
定义新的数据类型以及这些新的数据类型进行相互操作的方法
定义方式:
- class Cat
- {}
- class Cat:object
- {
- }
- C# 中所有的类都是默认由 object 类派生来的, 显示指定或者省略效果是一样的, 所以上面的两个例子是完全相同的.
- C# 中类包括: 抽象类, 密封类, 非抽象类
abstract: 表示修饰的类不完整, 也就是抽象类, 只能用做基类. 在使用是不能直接实例化,
不能使用 new 运算符.
sealed: 表示修饰的类不可派生, 也就是密封类.
base: 访问最近的基类, 也就是当前类继承的类
- class Cat:Animal
- {
- public void Cat()
- {
- base.Eat();
- }
- }
以上例子中 base 代表 Animal.
注意: base 只能在类的内部使用.
2 继承
2.1 继承定义
继承: 把两个或多个类的相同属性提取出来, 将这些属性合在一起建立父类!
2.2 使用
- class A
- {
- public void Sum(int i,int j)
- {
- int sum = i + j;
- Console.WriteLine("I am A ,my sum ={0}",sum);
- }
- }
- class B : A
- {
- public void Minus(int i,int j)
- {
- int minus = i - j;
- Console.WriteLine("I am B ,my minus ={0}", minus);
- this.Sum(3, 4);
- }
- }
- class InheritanceTest1
- {
- static void Main(string[] args)
- {
- B b = new B();
- b.Minus(3, 4);
- Console.Read();
- }
- }
结果: I am B ,my minus=-1
I am A ,my sum = 7
3 接口
- public interface IPolimorphism()
- {
- void Say();
- }
- using System;
- using System.Windows.Forms;
- namespace NorthWind
- {
- public class Red:IPolimorphism // 实现接口的方法
- {
- public void Say() // 不需要指定 override 关键字
- {
- MessageBox.Show("Red!");
- }
- }
- public class Yello:IPolimorphism
- {
- public void Say() // 不需要指定 override 关键字
- {
- MessageBox.Show("Yello!");
- }
- }
- }
- using System;
- using System.Windows.Forms;
- namespace NorthWind
- {
- public class MainFrm : System.Windows.Forms
- {
- [STAThread]
- static void Main()
- {
- IPolimorphism red = new Red();
- red.Say();
- IPolimorphism yello = new Yello();
- yello.Say();
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2665679.html