如果在同一个类中定义了多个具有相同名称的构造函数,则如果每个构造函数的参数不同,则将它们称为重载。
让我们看一个示例,以学习如何在C#中使用构造函数重载。
在示例中,我们有两个主题和一个“学生姓名”的字符串声明。
private double SubjectOne; private double SubjectTwo; string StudentName;
我们正在显示三个不同学科的学生的成绩。在我们的示例中,为显示构造函数重载,仅为学生3 rd显示名称。
Student s1 = new Student(); Student s2 = new Student(90); Student s3 = new Student("Amit",88, 60);
您可以尝试运行以下代码以在C#中实现构造函数重载。
using System; namespace Program { class Student { private double SubjectOne; private double SubjectTwo; string StudentName; public Student() { this.SubjectOne = 80; } public Student(double SubjectOne) { this.SubjectOne = SubjectOne; } public Student(string StudentName, double SubjectOne, double SubjectTwo) { this.SubjectOne = SubjectOne; this.SubjectTwo = SubjectTwo; this.StudentName = StudentName; } public double GetSubjectOneMarks() { return this.SubjectOne; } public double GetSubjectTwoMarks() { return this.SubjectTwo; } public string GetStudentName() { return this.StudentName; } } class Program { static void Main(string[] args) { Student s1 = new Student(); Student s2 = new Student(90); Student s3 = new Student("Amit",88, 60); Console.WriteLine("One"); Console.WriteLine("Subject One Marks: {0}", s1.GetSubjectOneMarks()); Console.WriteLine(); Console.WriteLine("Second"); Console.WriteLine("Subject One Marks: {0}", s2.GetSubjectOneMarks()); Console.WriteLine(); Console.WriteLine("Third"); Console.WriteLine("Student name: {0}", s3.GetStudentName()); Console.WriteLine("Subject One Marks: {0}", s3.GetSubjectOneMarks()); Console.WriteLine("Subject Two Marks: {0}", s3.GetSubjectTwoMarks()); Console.ReadKey(); } } }
输出结果
One Subject One Marks: 80 Second Subject One Marks: 90 Third Student name: Amit Subject One Marks: 88 Subject Two Marks: 60