列表作为参考传递

时间:2014-11-26 15:30:43

标签: c# list ienumerable pass-by-reference

由于列表是引用类型,为什么我在下面的示例中将missionList计数为0而不是4? 请解释一下这种行为

protected void AssignButton_Click(object sender, EventArgs e)
{
    List<string> membersIdList = new List<string>();
    List<Missions> missionsList = new List<Missions>();
    string selectedMembersName = SelectedMembersDetailsGet(membersIdList, missionsList); 

    //Here membersIdList count is "1" & missionsList count is "0"                      
}

private string SelectedMembersDetailsGet(List<string> membersIdList, List<Missions> missionsList)
{
    string selectedMembersName = string.Empty;
    IEnumerable<Missions> commonMissionsList = null;

    membersIdList.Add("XYZ");

    commonMissionsList = MissionsGet();  //Returns 4 records

    if (commonMissionsList != null)
    {
        missionsList = commonMissionsList.ToList(); 
    }
    return selectedMembersName;
}

2 个答案:

答案 0 :(得分:2)

引用类型按值传递。这意味着您在新变量中传递引用的地址(地址被复制到新的内存位置,传递一个)。

在您的子方法中,您将新列表重新分配给此新内存位置,而旧内存位置仍保留原始列表的地址。

另请参阅:http://msdn.microsoft.com/en-us/library/s6938f28.aspx

你应该做的是:

 private string SelectedMembersDetailsGet(List<string> membersIdList, List<Missions> missionsList)
 {
    string selectedMembersName = string.Empty;
    IEnumerable<Missions> commonMissionsList = null;

    membersIdList.Add("XYZ");

    commonMissionsList = MissionsGet();  //Returns 4 records

    if (commonMissionsList != null)
    {
        foreach(var mission in commonMissionsList)
        {
               missionsList.Add(mission);
        }
    }
    return selectedMembersName;
}

答案 1 :(得分:0)

为了能够通过方法参数返回新列表,您必须使用out关键字:

protected void AssignButton_Click(object sender, EventArgs e)
{
    List<string> membersIdList = new List<string>();
    List<Missions> missionsList = null;
    string selectedMembersName = SelectedMembersDetailsGet(membersIdList, out missionsList); 

    //Here membersIdList count is "1" & missionsList count is "0"                      
}

private string SelectedMembersDetailsGet(List<string> membersIdList, out List<Missions> missionsList)
{
    string selectedMembersName = string.Empty;
    IEnumerable<Missions> commonMissionsList = null;

    membersIdList.Add("XYZ");

    commonMissionsList = MissionsGet();  //Returns 4 records

    if (commonMissionsList != null)
    {
        missionsList = commonMissionsList.ToList(); 
    } 
    else 
    {
        missionList = null; // You must assign to missionList otherwise the compiler will throw an error.
    }
    return selectedMembersName;
}

out (C# Reference)

What's the difference between the 'ref' and 'out' keywords?