有人能告诉我,如何在主体中实现我的功能吗?所有的工作,但我想做一个目录的雇主,那么如何写雇主列表或大量?
class Catalog : Employe
{
Employe[] employes = new Employe[10];
Employe p1 = new Employe(14, "Mark", "James", 124151, "Coder", 4000);
public Catalog(int _age, string _firstName, string _lastName, int _id, string _job, int _salary) : base(_age, _firstName, _lastName, _id, _job, _salary)
{
employes[1] = p1;
}
public void CatalogLog()
{
for(int i = 0; i < employes.Length; i++)
Console.WriteLine(employes[i]);
}
}
class TestInheritence
{
public static void Main(string[] args)
{
Employe[] employes = new Employe[10];
}
}
我认为您没有用正确的逻辑设置继承层次结构。基类Employee
是可扩展的,包含基本方法:
public class Employee
{
private int _id;
private string _firstName;
public Employee(int id, string firstName)
{
_id = id;
_firstName = firstName;
}
public int GetID()
{
return _id;
}
public void SetID(int id)
{
if(id > 0)
_id = id;
}
public void Print()
{
Console.WriteLine("ID: {0}tFirst Name: {1}", this._id, this._firstName);
}
}
派生类允许对象通过向基类的属性添加新方法和属性来扩展:
public class Manager : Employee
{
private string _city;
public Manager(int id, string firstName, string city) : base(id, firstName)
{
_city = city;
}
public string GetCity()
{
return _city;
}
}
为了测试这两个类是如何工作的,您可以查看下面的应用程序代码:
public class Program
{
public static void Main()
{
Employee[] employees = new[]
{
new Employee(1, "Thomas"),
new Employee(2, "John"),
new Employee(3, "Erick"),
new Employee(4, "Ahmet"),
new Employee(5, "Sun")
};
employees[0].Print();
Manager manager = new Manager(6, "Johnson", "London");
manager.Print();
Console.WriteLine("City: {0}", manager.GetCity());
}
}
如果你想将员工添加到目录中,你可以有一个"添加"功能,将员工添加至目录:
class Catalog : Employe
{
List<Employe> employes = new List<Employe>();
public void AddEmployee(int _age, string _firstName, string _lastName, int _id, string _job, int _salary) : base(_age, _firstName, _lastName, _id, _job, _salary)
{
Employe p1 = new Employe(_age, _firstName, _lastName, _id, _job, _salary);
employes.Add(p1);
}
public void CatalogLog()
{
for(int i = 0; i < employes.Count(); i++)
Console.WriteLine(employes[i]);
}
}
class TestInheritence
{
public static void Main(string[] args)
{
Catalog catalog = new Catalog();
catalog.AddEmployee(14, "Mark", "James", 124151, "Coder", 4000);
// Add more employees.
}
}
但我认为这是一个错误的继承用例。通常,当类型之间存在"is-a"关系时,您希望继承。但"目录"不是"员工"的类型