我想在 Detail()
的继承方法中打印调用的(其中任何一个)子类的薪水。在这种情况下不能这样做。我将如何获得员工的所有其他详细信息的薪水。
这是代码
using System;
class Employee
{
public int ID;
public string Name;
public string Gender;
public string City;
public void Detail()
{
Console.WriteLine("Name: {0} \nGender: {1} \nCity: {2} \nID: {3}", Name, Gender, City, ID); //I want to get Yearly or Hourly Salary with these all
}
}
class PermanatEmp : Employee
{
public float YearlySalary;
}
class TempEmp : Employee
{
public float HourlySalary;
}
class Class4
{
static void Main()
{
PermanatEmp pe = new PermanatEmp();
pe.ID = 101;
pe.Name = "XYZ";
pe.Gender = "Male";
pe.City = "London";
pe.YearlySalary = 20000;
pe.Detail(); // how to get Salary with these all
}
}
最佳答案
您不能也不应该 - 无法保证雇员
有薪水。
相反,任何确实有薪水的类都可以覆盖ToString
以包括它想要的所有属性。顺便说一下,我建议重写 ToString
而不是使用只打印信息的 Detail
方法。
(作为旁注,我强烈建议您不要使用公共(public)可写字段。Use properties instead。)
关于c# - C#如何在父类的方法中调用子类的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31725406/