为什么我的foreach中的代码无法访问?(已经过单元测试的工作代码的确切副本)

Zub*_*air 4 c# foreach wcf unreachable-code

下面的代码是一个完美的代码的精确副本.不同之处在于此代码放在WCF服务应用程序项目中,而工作代码来自Windows窗体应用程序项目.foreach中的代码是无法访问的,这很奇怪,因为我之前测试过代码并且它有效,返回正确的值

public IEnumerable<Employee> GetStudentDetails(string username,string password)
    {
        var emp = agrDb.LoginAuthentication(username, password);//procedure in the database thats returning two values
                                                                //Namely: EmployeeFirstName and EmployeeLastName
        List<Employee> trainerList = new List<Employee>();

        foreach (var item in emp)
        {
            //unreachable code here
            Employee employ = new Employee();
            employ.EmployeeFirstName = item.EmployeeFirstName;
            employ.EmployeeLastName = item.EmployeeLastName;
            trainerList.Add(employ);
            //trainerList.Add(item.EmployeeLastName);
        }
        return trainerList;
    }
Run Code Online (Sandbox Code Playgroud)

小智 6

如果数组或集合在运行时未初始化,则foreach循环中的代码可以不可删除.

List<Employee> emp;

// Run when program starts, called from Program.cs
private void InitialiseApplication()
{
    emp = new List<Employee>;

    // Gather data for employees from... somewhere.
    DataAccess.GetEmployees(emp);
}

private void DoStuff()
{
    foreach (var item in emp)
    {
         // Do something.
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将带回警告,因为"emp"在设计时没有初始化.

我在代码中收到了相同的警告,包括在构造函数内的各个阶段.但是,运行时流程不会受到影响,因为到那时,"emp"已初始化.

您的代码可能就是这种情况.检查程序"emp"流程初始化期间的位置和时间.如果视线不明显,你可能需要"进入"程序来实现这个目标.