如何在继承的类程序的构造函数中传递参数?

问题描述 投票:0回答:3

这是我的代码,这是什么错误?以及如何解决。如上所述,构造函数是一种方法,它将不包含任何返回类型。如果要使用c#创建构造函数,则需要创建一个名称与类名称相同的方法。

class Program
    {
        public static int number;
        public static string name;
        public static float salary = 20000;
        static void Main(string[] args)
        {

            Console.WriteLine("Welcome");
            Console.WriteLine("Enter Your Name: ");
            name = Console.ReadLine();
            Employee System = new Employee("Sameed", 20000f);
            Bonus b1 = new Bonus();
            //b1.Employee(name, salary);
            b1.Salary(salary);
            b1.Bonuses();
            Display(number);
            Display(name,number);
    }
    static void Display(int n)
{

    Console.WriteLine("Employee Number is: " +n);
}
    static void Display(string name, int num)
{
    Console.WriteLine("Congratulations {0}, your Employee number has been generated {1}",name,num);
}
}
public class Employee
{
    public Employee(string n, float s)
    {
        Console.WriteLine("Hello Mr. {0}, Your Salary is {1}", n, s);
    }
}
public class Director:Employee
{
    public void Salary(float s)
    {
        Console.WriteLine("Your Salary is: " + s);
    }
}
    public class Bonus:Director
    {
        public void Bonuses()
        {

            int bonus = 40000;
            Console.WriteLine("Your Bonus is: " + bonus);
        }
    }

错误:雇员'不包含带有0个参数的构造函数

c# class constructor multiple-inheritance
3个回答
1
投票

由于Director类继承了Employee类,因此应使用基类的构造函数创建实际实例。因此,在您的代码中也将构造函数添加到Director类中,然后调用基类构造函数,例如

public Director(string n, float s) : base(n, s)
{
}

没有该编译器会产生错误

错误CS7036:没有给出与必需的形式参数

Bonus类应该做同样的事情>

public Bonus(string n, float s) : base(n, s)
{
}

Bonus实例的创建将如下

Bonus b1 = new Bonus(name, salary);

0
投票

因此,您的DirectorEmployee。而且Employee只能用namesalary 2个值实例化。因此,由于您的DirectorEmployee,意味着对他也适用相同的规则-他必须


0
投票
任何继承的类构造函数都必须将必需的参数传递给基类。因此,公共主管:基础(此处为必需值)。如果您不想将值传递给Director构造函数,则可以这样做。但是,您仍然必须将某些内容传递给基类。例如:
© www.soinside.com 2019 - 2024. All rights reserved.