c# 里式转换
is—表示类型转换,如果转换成功就返回true否则就是false
as—表示类型转换,如果转换成功就返回该对象 否则就是null
1)、子类可以赋值给父类:如果有一个地方需要一个父类作为参数,我们可以给一个子类代替。(配合is关键字判断是否可以转换)
(如:Person s = new Student();)
2)、如果这个父类中装的是子类对象,那么可以将这个父类强转为子类对象。
(如:Student p = (Student)s;)
子类对象可以调用父类中的成员,但是父类对象永远都只能调用自己的成员。
class Program
{
static void Main(string[] args)
{
//子类可以赋值给父类:如果有一个地方需要一个父类作为参数,我们可以给一个子类代替
Father dg = new Children();
dg.SayHello(); //dg装的是子类,但是仍是父类,父类对象永远都只能调用自己的成员
//如果这个父类中装的是子类对象,那么可以将这个父类强转为子类对象。
Father ss = new Children();
Children fatherSwitch = (Children)ss;
fatherSwitch.SayHello(); //变为子类
//转换判断 is(bool) as(obj or null)
if (dg is Children)
{
Console.WriteLine("我是父类装载的是子类");
}
else
{
Console.WriteLine("");
}
//转换判断 as(obj or null)
Children a = ss as Children;//ss转换children成功返回obj,否则null
Console.ReadKey();
}
}
public class Father
{
public string a = "我是父类属性";
public void SayHello()
{
Console.WriteLine("我是父类");
}
}
public class Children:Father
{
public string b = "我是子类属性";
public void SayHello()
{
Console.WriteLine("我是子类");
}
}
练习:随机执行不同子类方法
static void Main(string[] args)
{
Teacher li = new Teacher();
Student wang = new Student();
Repoter zhang = new Repoter();
//创建父类数组用来装载子类
People[] MyChildren = new People[3];
//for循环装载子类
for (int i = 0; i < MyChildren.Length; i++)
{
Random rm = new Random();
int rms = rm.Next(0, 3); //random随机数短时间内相同
switch (rms)
{
case 0 :MyChildren[i] = new Teacher();
break;
case 1:
MyChildren[i] = new Student();
break;
case 2:
MyChildren[i] = new Repoter();
break;
}
}
for (int i = 0; i <MyChildren.Length; i++)
{
if (MyChildren[i] is Student ) //is判断
{
((Student)MyChildren[i]).SayHello();//注意写法
}
else if(MyChildren[i] is Teacher)
{
((Teacher)MyChildren[i]).SayHello();
}
else
{
((Repoter)MyChildren[i]).SayHello();
}
}
Console.ReadKey();
}
}
public class People
{
public void SayHello()
{
Console.WriteLine("我是父类");
}
}
public class Teacher:People
{
public new void SayHello() //new显式隐藏父类同名函数,即覆盖
{
Console.WriteLine("我是教师");
}
}
public class Student : People
{
public new void SayHello()
{
Console.WriteLine("我是学生");
}
}
public class Repoter: People
{
public new void SayHello()
{
Console.WriteLine("我是记者");
}
}

浙公网安备 33010602011771号