关于OOPS&C#中的编码风格

Mou*_*Mou 1 c# oop

我通过一个代码示例,我已经看到了一种不同的方式来创建一个实例.

所以这里的代码

public interface IEmployee
{
    System.Int32? EmployeeID { get; set; }
    System.String FirstName { get; set; }
    System.String LastName { get; set; }
    System.DateTime DateOfBirth { get; set; }
    System.Int32? DepartmentID { get; set; }
    System.String FullName();
    System.Single Salary();
}

public class Employee : IEmployee
{
    #region Properties

    public System.Int32? EmployeeID { get; set; }
    public System.String FirstName { get; set; }
    public System.String LastName { get; set; }
    public System.DateTime DateOfBirth { get; set; }
    public System.Int32? DepartmentID { get; set; }

    #endregion

    public Employee(
        System.Int32? employeeid
        , System.String firstname
        , System.String lastname
        , System.DateTime bDay
        , System.Int32? departmentID
    )
    {
        this.EmployeeID = employeeid;
        this.FirstName = firstname;
        this.LastName = lastname;
        this.DateOfBirth = bDay;
        this.DepartmentID = departmentID;
    }

    public Employee() { }

    public System.String FullName()
    {
        System.String s = FirstName + " " + LastName;
        return s;
    }

    public System.Single Salary()
    {
        System.Single i = 10000.12f;
        return i;
    }
}

    private List<IEmployee> myList =  new List<IEmployee> { new Employee(1, "John", "Smith", new DateTime(1990, 4, 1), 1), 
            new Employee(2, "Gustavo", "Achong", new DateTime(1980, 8, 1), 1), 
            new Employee(3, "Maxwell", "Becker", new DateTime(1966, 12, 24), 2), 
            new Employee(4, "Catherine", "Johnston", new DateTime(1977, 4, 12), 2), 
            new Employee(5, "Payton", "Castellucio", new DateTime(1959, 4, 21), 3), 
            new Employee(6, "Pamela", "Lee", new DateTime(1978, 9, 16), 4) };
Run Code Online (Sandbox Code Playgroud)

所以我只想知道为什么代码应该用IEmployee创建列表实例为什么不是Employee.

在这里我们可以编码

private List<Employee> myList =  new List<Employee> { new Employee(1, "John", "Smith", new DateTime(1990, 4, 1), 1), 
        new Employee(2, "Gustavo", "Achong", new DateTime(1980, 8, 1), 1), 
        new Employee(3, "Maxwell", "Becker", new DateTime(1966, 12, 24), 2), 
        new Employee(4, "Catherine", "Johnston", new DateTime(1977, 4, 12), 2), 
        new Employee(5, "Payton", "Castellucio", new DateTime(1959, 4, 21), 3), 
        new Employee(6, "Pamela", "Lee", new DateTime(1978, 9, 16), 4) };
Run Code Online (Sandbox Code Playgroud)

它也有效....他们为什么要使用IEmployee.为什么编码器使用IEmployee而不是Employee,所以必须有一些特定的目标.所以我只需要知道使用IEmployee的目标.我正在寻找好的解释.请指导我.谢谢.

Jim*_*lle 8

List<IEmployee>如果您想要多个实现,使用a 允许代码保持灵活性IEmployee.例如,您可能希望拥有Employee : IEmployeeManager : IEmployee,并且List<IEmployee>允许列表包含两者