我正在將「引用類型」傳遞給函數「BY VAL」。在函數中,我試圖修改foreach循環中的引用類型。引用類型對象沒有得到更新,但返回更新的對象
然後當涉及到調用者,我通過的對象 沒有得到更新。 但返回更新的對象。
我給出了下面這個問題的例子。
有人可以幫助我,爲什麼它會發生這樣的花費幾分鐘嗎?
下面是方法GetStudents(),FilterStudents(), 班,學生,老師,SSCClass,
SSCClass - 包含教師陣列。 老師 - 包含學生數組。
public void GetStudents()
{
Student[] sscStudentsOne = new Student[] { new Student { V_SId = 1, V_SName = "Kumar" }, new Student { V_SId = 2, V_SName = "Varun" }, new Student { V_SId = 3, V_SName = "Murthy" } };
Student[] sscStudentsTwo = new Student[] { new Student { V_SId = 4, V_SName = "Sathya" }, new Student { V_SId = 5, V_SName = "Krishna" }, new Student { V_SId = 6, V_SName = "Bindu" } };
Teacher[] sscTeachers = new Teacher[] { new Teacher { V_tId = 1, V_tName = "Jyothi", V_Students = sscStudentsOne }, new Teacher { V_tId = 2, V_tName = "Srinivas", V_Students = sscStudentsTwo } };
SSCClass objSSCClass = new SSCClass();
objSSCClass.V_sscTeachers = sscTeachers;
SSCClass objSSCClassFiltered = FilterStudents(objSSCClass);
// Problem :-
// in objSSCClass Kumar is getting removed but Sathya from second teachere is not getting removed.
// in objSSCClassFiltered Kumar and Sathya are Getting removed as we did.
// We need objSSCClass object to be updated successfully .. as we can not return this to caller method in my project.
}
public SSCClass FilterStudents(SSCClass objSSCClasstobeFiltered)
{
foreach (Teacher item in objSSCClasstobeFiltered.V_sscTeachers)
{
// here a method will be called and does the below
// removes Students based on some criteria
// Say,
// Remove Student Kumar from first teacher.
// Remove Student Sathya from second teacher
}
// after filtering Students return the SSC Class object
return objSSCClasstobeFiltered;
}
public class Student
{
int v_sId;
public int V_SId
{
get { return v_sId; }
set { v_sId = value; }
}
string v_SName;
public string V_SName
{
get { return v_SName; }
set { v_SName = value; }
}
}
public class Teacher
{
int v_tId;
public int V_tId
{
get { return v_tId; }
set { v_tId = value; }
}
string v_tName;
public string V_tName
{
get { return v_tName; }
set { v_tName = value; }
}
Student[] v_Students;
public Student[] V_Students
{
get { return v_Students; }
set { v_Students = value; }
}
}
public class SSCClass
{
Teacher[] v_sscTeachers;
public Teacher[] V_sscTeachers
{
get { return v_sscTeachers; }
set { v_sscTeachers = value; }
}
}
後功能的代碼,不要安靜地理解問題的核心。 – SimpleVar 2013-05-05 04:11:37
是什麼問題? – 2013-05-05 04:11:59
你可以添加實際的代碼,而不僅僅是評論,謝謝。 – Guy 2013-05-05 04:29:57