C# 中的构造函数重载
csharpprogrammingserver side programming
当在同一个类中定义多个同名的构造函数时,如果每个构造函数的参数不同,则它们被称为重载。
让我们看一个例子来学习如何在 C# 中使用构造函数重载。
在示例中,我们有两个科目和一个学生姓名的字符串声明。
private double SubjectOne; private double SubjectTwo; string StudentName;
我们显示了三个学生在不同科目的成绩。对于我们的示例,为了显示构造函数重载,仅显示学生 3rd 的姓名。
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