2019-01-15

一、.NET基础概念《面向对象-继承》

继承:LSP里氏替换原则(通过代码说明下,声明父类类型变量,指向子类类型对象,以及调用方法时的一些问题)

继承注意点:
(1).子类执行构造函数之前,会默认执行父类的无参构造函数,因此如果父类执行有参构造函数时,必须实现自己的无参构造函数,否则,会报错。
//解决办法1,在父类实现无参构造函数

public  class Person 
{
   public string Name {get;set;}
   public int Age {get;set;}
   public Person(string name, int age)
   {
      this.Name = name;
      this.Age = age;
   }

   public Person()
   { 
   }
}

class Student:Person
{
   public int Sid {get;set;} 
   public Person(string name, int age, int sid)
   {
      this.Name = name;
      this.Age = age;
      this.Sid = sid;
   }
}

//解决办法2,在子类实现构造函数时,同时继承实现父类有参构造函数

public  class Person 
{
   public string Name {get;set;}
   public int Age {get;set;}
   public Person(string name, int age)
   {
      this.Name = name;
      this.Age = age;
   } 
}

public  class Student:Person
{
   public int Sid {get;set;} 
   public Person(string name, int age, int sid):base(name,age)  //在调用父类构造函数之前,现调用父类构造函数
   { 
      this.Sid = sid;
   }
}

(2)this在构造函数中的应用:可以封装多个不同参数的构造函数

public  class Person 
{
   public string Name {get;set;}
   public int Age {get;set;}

   public Person(string name):this(name,0)
   { 
   } 

   public Person(string name, int age)
   {
      this.Name = name;
      this.Age = age;
   } 
}
 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。