C# 中的构造函数重载
如果同一个类中定义了多个具有相同名称的构造函数,并且每个构造函数的参数不同,则称这些构造函数为重载。
让我们看一个示例来了解如何在 C# 中使用构造函数重载。
在这个示例中,我们有两个科目和针对学生姓名的一个字符串声明。
private double SubjectOne; private double SubjectTwo; string StudentName;
我们正在显示三个学生在不同科目中的成绩。对于我们的示例,为了演示构造函数重载,仅显示第 3 个学生的姓名。
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
广告