関数「BY VAL」に「参照型」を渡しています。関数では、foreach ループで参照型を変更しようとしています。
次に、呼び出し元になると、渡したオブジェクトが更新されません。しかし、更新されたオブジェクトを返します。
この問題の例を以下に示します。
数分かけて、なぜこのようなことが起こっているのか、誰かが私を助けてくれますか?
以下はメソッドGetStudents()、FilterStudents()、classes、Student、Teacher、SSCClass、
SSCClass - Teachers 配列が含まれています。教師 - 生徒の配列が含まれます。
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; }
}
}