코드가 있습니다. 수업이 있습니다.
public class TestClass
{
private string String1 = "";
private List<string> Strings = new List<string>();
public TestClass(string String1, List<string> Strings)
{
this.String1 = String1;
this.Strings = Strings;
} // end constructor.
// Associated get/set methods.
} // end class.
그런 다음 (다른 클래스에서 이것을 사용하는 일부 코드) :
public TestMethod()
{
List<string> Strings = new List<string>();
List<TestClass> MasterList = new List<TestClass>();
int Counter = 0;
string Name = " ... " // <- updated every time.
while(Condition1)
{
if(Condition2)
{
Strings.Add(Counter.ToString());
}
else
{
MasterList.Add(new TestClass(Name, Strings));
Name = // ... <- name updated here.
Strings.Clear(); // Clear array.
} // end if.
} // end while.
} // end method.
처음에는의 첫 번째 요소 MasterList
가 "Name1"이고 목록에 "1, 2, 3"이 포함됩니다. 다음에 MasterList
"Name2"및 "4, 5, 6"이 포함되지만 이제 첫 번째 요소에는 "1, 2, 3"이 아닌 "4, 5, 6"이 포함됩니다. 얼마 동안 실행하면 "Name1", "Name2"가 매번 업데이트되지만 모든 요소 목록은 정확히 동일한 내용입니다. 예를 들어 출력 내용은 무엇입니까?
"Name1" -> "1, 2, 3"
"Name2" -> "4, 5, 6"
"Name3" -> "7, 8, 9"
실제로 일어나는 일 :
"Name1" -> "7, 8, 9"
"Name2" -> "7, 8, 9"
"Name3" -> "7, 8, 9"
내가 여기서 뭘 잘못했는지 알아 내려고하는데, 어떤 아이디어라도? 이것은 일종의 참조 문제입니까?
감사! 홍옥
항상 동일한 목록을 재사용하고 있습니다.
MasterList.Add(new TestClass(Name, Strings)); //<<- Strings is always the same instance
따라서 목록에서 변경 한 사항은 모든 하위 클래스에 전파되고 List는 참조 객체이므로 함수에 전달할 때 데이터 구조가 아니라 객체에 대한 참조를 전달하므로 모두 클래스는 동일한 객체를 가리 킵니다.
이를 해결하는 매우 간단한 방법은 다음을 대체하는 것입니다.
Strings.Clear(); // Clear array.
와:
Strings = new List<string>();
이런 식으로 매번 새 인스턴스에 대한 참조를 전달합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다