您好,登錄后才能下訂單哦!
代碼如下:
Person.cs文件。
using System;
using System.Collections.Generic;
using System.Text;
namespace InheritDemo
{
public class Person
{
private string id;
public string Id
{
get
{
return id;
}
set
{
id = value;
}
}
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private int age;
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
private string gender;
public string Gender
{
get
{
return gender;
}
set
{
gender = value;
}
}
public Person(string name1, int age1, string gender1)
{
name = name1;
age = age1;
gender = gender1;
}
public void Display()
{
Console.WriteLine("{0}是{1}性,年齡為{2}",this.name,this.gender,this.age);
}
}
public class Student : Person
{
private string class1;
public string Class
{
get
{
return class1;
}
set
{
class1 = value;
}
}
private string department;
public string Department
{
get
{
return department;
}
set
{
department = value;
}
}
private string no;
public string No
{
get
{
return no;
}
set
{
no = value;
}
}
public void Study()
{
Console.WriteLine("學生在學校學習。");
Console.Read();
}
}
}
Program.cs文件。
using System;
using System.Collections.Generic;
using System.Text;
namespace InheritDemo
{
class Program
{
static void Main(string[] args)
{
Person objPerson = new Person("XXX",XX,"X");
objPerson.Display();
Student objStudent = new Student();
objStudent.Name = "XXX";
objStudent.Age = XX;
objStudent.Gender = "X";
objStudent.Class = "XXXXXXXXX";
objStudent.Display();
Console.Read();
}
}
}
錯誤:“Person”方法沒有采用“0”個參數的重載。
原因:子類的構造函數沒有使用base指明調用父類哪個構造函數。
解決辦法:
using System;
using System.Collections.Generic;
using System.Text;
namespace InheritDemo
{
public class Person
{
private string id;
public string Id
{
get
{
return id;
}
set
{
id = value;
}
}
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private int age;
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
private string gender;
public string Gender
{
get
{
return gender;
}
set
{
gender = value;
}
}
public Person() { } //隱式的調用,base(),父類要提供無參的構造函數。
public Person(string name1, int age1, string gender1)
{
name = name1;
age = age1;
gender = gender1;
}
public void Display()
{
Console.WriteLine("{0}是{1}性,年齡為{2}",this.name,this.gender,this.age);
}
}
public class Student : Person
{
private string class1;
public string Class
{
get
{
return class1;
}
set
{
class1 = value;
}
}
private string department;
public string Department
{
get
{
return department;
}
set
{
department = value;
}
}
private string no;
public string No
{
get
{
return no;
}
set
{
no = value;
}
}
public Student() { } //隱式的調用,base(),父類要提供無參的構造函數。
public void Study()
{
Console.WriteLine("學生在學校學習。");
Console.Read();
}
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。