C#中结构的构造方法重载

在同一程序中定义多个构造函数时,称为构造函数重载。在C#中,我们可以在以下基础上重载构造函数:

  1. 参数类型

  2. 参数个数

  3. 参数顺序

在给定的示例中,我们有两个参数化的构造函数(因为我们知道构造函数名称与类名称相同),它们具有不同的参数类型。

第一个构造函数具有以下声明:

public Student( int x, string s)

第二,具有:

public Student(string s, int x)

这两个声明具有不同类型的参数,因此可以实现构造函数重载而不会出现任何问题。

示例

using System;
using System.Collections;

namespace ConsoleApplication1
{

    struct Student
    {
        public int roll_number;
        public string name;

        public Student( int x, string s)
        {
            roll_number = x;
            name = s;
        }

        public Student(string s, int x)
        {
            roll_number = x;
            name = s;
        }

        public void printValue()
        {
            Console.WriteLine("Roll Number: " + roll_number);
            Console.WriteLine("Name: " + name);
        }
    }
    class Program
    {
        static void Main()
        {
            Student S1 = new Student(101,"Shaurya Pratap Singh");
            Student S2 = new Student("Pandit Ram Sharma",102);

            S1.printValue();
            S2.printValue();
        }
    }
}

输出结果

Roll Number: 101
Name: Shaurya Pratap Singh
Roll Number: 102
Name: Pandit Ram Sharma