Computer >> Máy Tính >  >> Lập trình >> C#

Nạp chồng khối lệnh trong C #

Khi nhiều hơn một hàm tạo có cùng tên được xác định trong cùng một lớp, chúng được gọi là quá tải, nếu các tham số khác nhau đối với mỗi hàm tạo.

Hãy để chúng tôi xem một ví dụ để tìm hiểu cách làm việc với Nạp chồng khối lệnh trong C #.

Trong ví dụ này, chúng ta có hai chủ thể và một khai báo chuỗi cho Tên sinh viên.

private double SubjectOne;
private double SubjectTwo;
string StudentName;

Chúng tôi đang hiển thị kết quả của ba học sinh trong các môn học khác nhau. Ví dụ của chúng tôi, để hiển thị quá tải hàm tạo, tên chỉ được hiển thị cho học sinh 3 rd .

Student s1 = new Student();
Student s2 = new Student(90);
Student s3 = new Student("Amit",88, 60);

Bạn có thể thử chạy đoạn mã sau để thực hiện nạp chồng hàm tạo trong C #.

Ví dụ

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();
      }
   }
}

Đầu ra

One
Subject One Marks: 80

Second
Subject One Marks: 90

Third
Student name: Amit
Subject One Marks: 88
Subject Two Marks: 60