public class virtual方法
{
public void SayName()
{
Person[] pers = new Person[2];
pers[0] = new Amaercan();
pers[1] = new Chinese();
for (int i = 0; i < pers.Length; i++)
{
//不能忍 如果国家越来越来 没法写了 我要一句话 给他搞出来
if (pers[i] is Amaercan)
(pers[i] as Amaercan).SayName();
else if (pers[i] is Chinese)
(pers[i] as Chinese).SayName();
}
Console.ReadLine();
}
}
public class Chinese : Person
{
public void SayName()
{
Console.WriteLine("中国");
}
}
public class Amaercan : Person
{
public void SayName()
{
Console.WriteLine("USA");
}
}
public class Person
{
public string Name { get; set; }
public string Sex { get; set; }
}
Chenies和Amarican都有各自的SayName方法,如果想要直接用person类new的话,person类没有SayName方法,是 . 不出来的 这时只能先判断他是哪个,再里式转换 调用SayName
如果明天新加了 Japan 那么又要加if else
if (pers[i] is Amaercan)
(pers[i] as Amaercan).SayName();
else if (pers[i] is Chinese)
(pers[i] as Chinese).SayName();
else if (pers[i] is Japan)
(pers[i] as Japan).SayName();
这太麻烦了,于是我想用一句话解决,给person类添加了
public class virtual方法
{
public void SayName()
{
Person[] pers = new Person[2];
pers[0] = new Amaercan();
pers[1] = new Chinese();
for (int i = 0; i < pers.Length; i++)
{
//不能忍 如果国家越来越来 没法写了 我要一句话 给他搞出来
//if (pers[i] is Amaercan)
// (pers[i] as Amaercan).SayName();
//else if (pers[i] is Chinese)
// (pers[i] as Chinese).SayName();
pers[i].SayName();
}
Console.ReadLine();
}
}
public class Person
{
public string Name { get; set; }
public string Sex { get; set; }
public void SayName()
{
Console.WriteLine("地球人");
}
}
结果发现,调用sayname方法时,全部调用的是父类的方法,全都成为了地球人
于是有了我给父类SayName加上 virtual 将父类的方法变为虚方法;
子类的SayName用override重写,变为自己想要的内容
public class virtual方法
{
public void SayName()
{
Person[] pers = new Person[2];
pers[0] = new Amaercan();
pers[1] = new Chinese();
for (int i = 0; i < pers.Length; i++)
{
//不能忍 如果国家越来越来 没法写了 我要一句话 给他搞出来
//if (pers[i] is Amaercan)
// (pers[i] as Amaercan).SayName();
//else if (pers[i] is Chinese)
// (pers[i] as Chinese).SayName();
pers[i].SayName();
}
Console.ReadLine();
}
}
public class Chinese : Person
{
public override void SayName()
{
Console.WriteLine("中国");
}
}
public class Amaercan : Person
{
public override void SayName()
{
Console.WriteLine("USA");
}
}
public class Person
{
public string Name { get; set; }
public string Sex { get; set; }
public virtual void SayName()
{
Console.WriteLine("地球人");
}
}
结果是