1 抽象类: 关键字(abstract):
特点:1)抽象类不能实体化,要调用只能创建子类并继承抽象类方法,将子类实例化后再从子类中调用;
2) 抽象类可以有抽象方法(抽象方法只有abstract+方法名 ,没有参数。若调用需在子类重写方法),也可以有实际方法
3) 抽象方法只能存在抽象类中,抽象类只能做父类。
2 接口 :关键字 (interface ):
特点:1)不是类就是拿来当父类的
2) 接口中不能有任何实际性的方法,所有的方法都是抽象的。
3)不需要加修饰符,里边的全部内容都是公开的。
4)调用内容只能创建子类并将子类实例化从子类中调用全部继承的内容;
例:创建接口
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { interface Jiekou //这是创建的接口 { } }
如果只继承接口中的一项,那么会出现下列问题 ,如图:
这就是接口里的其他方法 A1,A2,A3没有被继承,可以右击接口名称jiekou,然后在点击快速操作,再点击实现接口就可以把接口里的方法全部继承
3 object (对象) :是所有数据类型的祖宗
4 is 和as 类型转换运算符
1)is 的作用 :判断某个类型或变量是否是某个类型,返回的是bool类型:
例:
假设集合中有四种类型,并且只知道其中一个类型是随机数 找这个类型并且让他去1-11之间的随机数
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { int a = 10; string b = "aaa"; Random c = new Random(); student d = new student(); ArrayList arr = new ArrayList(); arr.Add(a); arr.Add(b); arr.Add(c); arr.Add(d); //遍历 foreach ( object x in arr ) { Random r = (Random)x; 将x强制转化并且赋值给随机数r Console.WriteLine(r.Next(1,11)); 打印r 1-11 的随机数 } Console.ReadKey(); } } }
因为四个类型中有不能转换的类型所以会出现以下错误:
加上特定条件,那么就没问题了例如:
static void Main(string[] args) { int a = 10; string b = "aaa"; Random c = new Random(); student d = new student(); ArrayList arr = new ArrayList(); arr.Add(a); arr.Add(b); arr.Add(c); arr.Add(d); foreach ( object x in arr ) { if (x is Random) //当x是random类型是才能转换 { Random r = (Random)x; Console.WriteLine(r.Next(1,11)); } } Console.ReadKey();
as 就是类型装换的方式,如果某个对象能转换成目标对象,那么他会转换成目标对象,否则返回一个null值不会抛出异常,这时只需判断 X 是不是为空就行
例:
class Program { static void Main(string[] args) { int a = 10; string b = "aaa"; Random c = new Random(); student d = new student(); ArrayList arr = new ArrayList(); arr.Add(a); arr.Add(b); arr.Add(c); arr.Add(d); foreach ( object x in arr ) { Random r = x as Random; if ( x!=null) //判断 x是不是为空 { Console.WriteLine(r.Next(1, 11)); } } Console.ReadKey(); } } }