文章目录
缘起
- 接触到C#的好的学习资料是一种幸运,就我使用的教材真的不怎么样
- 所以尽可能将自己接触的东西多研究多分析
案例
子类父类:都只有无参构造
internal class Program
{
class Person
{
public Person()
{
Console.WriteLine("Person.");
}
}
class DaBai : Person
{
public DaBai()
{
Console.WriteLine("Da Bai");
}
}
static void Main(string[] args)
{
Person person = new Person();
Console.WriteLine("------");
DaBai daBai = new DaBai();
Console.WriteLine("------");
Person person2 = new DaBai();
Console.WriteLine("------");
try
{
DaBai daBai1 = (DaBai)new Person();
}catch(Exception e)
{
Console.WriteLine(e);
}
}
}

子类父类:子类有参,父类无参
internal class Program
{
class Person
{
public Person()
{
Console.WriteLine("Person.");
}
}
class DaBai : Person
{
public DaBai()
{
Console.WriteLine("Da Bai");
}
public DaBai(string s)
{
Console.WriteLine("Xiao bai");
}
}
static void Main(string[] args)
{
Person person = new Person();
Console.WriteLine("------");
DaBai daBai = new DaBai();
Console.WriteLine("------");
DaBai daBai2 = new DaBai("s");
Console.WriteLine("------");
Person person2 = new DaBai();
Console.WriteLine("------");
Person person1 = new DaBai("p");
Console.WriteLine("------");
try
{
DaBai daBai1 = (DaBai)new Person();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}

子类父类:子、父类都有无参、有参
internal class Program
{
class Person
{
public Person()
{
Console.WriteLine("Person.");
}
public Person(string s)
{
Console.WriteLine("P");
}
}
class DaBai : Person
{
public DaBai()
{
Console.WriteLine("Da Bai");
}
public DaBai(string s)
{
Console.WriteLine("Xiao bai");
}
}
static void Main(string[] args)
{
Person person = new Person();
Console.WriteLine("------");
Person person1 = new Person("p");
Console.WriteLine("------");
DaBai daBai = new DaBai();
Console.WriteLine("------");
DaBai daBai2 = new DaBai("s");
Console.WriteLine("------");
Person person2 = new DaBai();
Console.WriteLine("------");
Person person3 = new DaBai("p");
Console.WriteLine("------");
try
{
DaBai daBai1 = (DaBai)new Person();
}
catch (Exception e)
{
Console.WriteLine(e);
}
try
{
DaBai daBai1 = (DaBai)new Person("s");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}

子类父类:父类只有有参构造,子类无参、有参都有
class Person
{
public Person(string s)
{
Console.WriteLine("P");
}
}
class DaBai : Person
{
public DaBai()
{
Console.WriteLine("Da Bai");
}
public DaBai(string s)
{
Console.WriteLine("Xiao bai");
}
}
class Program
{
static void Main(string[] args)
{
DaBai daBai = new DaBai("s");
Console.ReadKey();
}
}
分析·总结·疑问
- 在实例化对象时,会执行无参、有参的构造函数
- 如果实现了有参构造,就必须实现无参构造;否则报错
- 向上转型:【父类变量引用子类对象】一般不会出错,实例化的还是子类对象
- 向下转型:【子类变量引用父类对象】需要显示指定转换类型【即强制类型转换】
- 子类在实例化的时候,构造函数的执行默认第一行会执行父类的无参构造函数,然后再继续再执行子类的构造函数
- 关于向下转型失败的研究,希望有大佬可以给出解释!