C#基类构造函数参数

时间:2013-11-26 20:17:22

标签: c#

我学习C#。我想看看实现继承的最佳方法是什么。我有一个Employee基类和一个PartTime派生类。 Employee类只接收名字和姓氏,并有一个打印全名的方法。

我想知道传递名字和姓氏的正确方法是什么,这样当我只调用PartTime类时,我也应该能够从调用程序中打印全名。目前它显示为空白全名:

class Program
{
    static void Main(string[] args)
    {
        Employee emp = new Employee("John", "Doe");
        // emp.PrintFullName();

        PartTime pt = new PartTime();

        float pay=pt.CalcPay(10, 8);
        pt.PrintFullName();  

        Console.WriteLine("Pay {0}", pay);
        Console.ReadKey();
    }
}

public class Employee
{
    string _firstName;
    string _last_name;

    public Employee(string FName, string LName)
    {
        _firstName = FName;
        _last_name = LName;
    }

    public Employee() { } 

    public void PrintFullName()
    {
        Console.WriteLine("Full Name {0} {1} ", _firstName, _last_name);
    }
}

public class PartTime : Employee
{
    public float CalcPay(int hours, int rate)
    {
        return hours * rate;
    }
}

3 个答案:

答案 0 :(得分:9)

您可以从您派生的类中调用基类构造函数,如下所示:

public class PartTime : Employee
{
    public PartTime(string FName, string Lname)
         : base(FName, LName)
    { }
}

然后创建它,

PartTime pt = new PartTime("Part", "Time");

答案 1 :(得分:1)

试试这个:

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    //method implementations removed for clarity

}

public class PartTime:Employee
{
    public PartTime(string firstName, string lastName)
        : base(firstName, lastName)
    {

    }
}

请注意,如果在PartTime类中需要进一步的初始化逻辑,那么基本构造函数将在派生构造函数中的任何代码之前运行

答案 2 :(得分:0)

您想要向PartTime添加一个构造函数,该构造函数将第一个和最后一个名称传递给基础构造函数

public PartTime(string fName, string lName) : base(fName, lName) {
}

或者您可以在Employee上创建名字公共属性,这些属性将由PartTime继承。然后,您可以在创建任一实例时初始化它们,而无需维护PartTime构造函数。

class Program
{
    static void Main(string[] args)
    {
        Employee emp = new Employee { FirstName = "John", LastName = "Doe" };
        emp.PrintFullName();

        PartTime pt = new PartTime  { FirstName = "Jane", LastName = "Doe" };

        float pay=pt.CalcPay(10, 8);
        pt.PrintFullName();  

        Console.WriteLine("Pay {0}", pay);
        Console.ReadKey();
    }
}

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public void PrintFullName()
    {
        Console.WriteLine("Full Name {0} {1} ", FirstName, LastName);
    }
}

public class PartTime : Employee
{
    public float CalcPay(int hours, int rate)
    {
        return hours * rate;
    }
}