사용자 정의 클래스의 인스턴스를 Session에 넣은 다음 가져 오면 세션에있는 항목에 대한 참조가 아닌 세션에있는 항목의 사본으로 나올 필요가 있습니다. 여기에 내가 가진 것이있다. 예를 들어서 물을 뿌린다.세션에서 객체 복사/복제
protected void btnSubmit_Click(object sender, EventArgs e)
{
Company selectedCompany = new Company("1234"); //a company code
selectedCompany.AnotherClass.Value1 = "hello";
Session["OLD.Company"] = selectedCompany;
Company newCompany = (Company)Session["OLD.Company"]; //I want this to be a COPY of what's in Session, not a reference to it.
newCompany.AnotherClass.Value1 = "goodbye";
Session["NEW.Company"] = newCompany;
}
I 통해 단차 세션 변수를 감시하고 OLD.Company 및 NEW.Company BOTH 대한 AnotherClass.Value1 위 결과 코드로 설정되고 "안녕."
초기 Google 검색은 회사 클래스에서 IClonable을 구현하는 방향으로 나를 가리키고 있습니다. 나는 다음을 시도했지만 아무 소용이 : 다음
public class Company : ICloneable
{
//properties...
//constructors...
public object Clone()
{
return this.MemberwiseClone();
}
}
및 ...
protected void btnSubmit_Click(object sender, EventArgs e)
{
Company oldCompany = (Company)Session["OLD.Company"];
Company newCompany = (Company)oldCompany.Clone();
newCompany.AnotherClass.Value1 = "goodbye";
Session["NEW.Company"] = newCompany;
}
여전히 OLD.Company 및 NEW.Company BOTH가 "안녕"것에 대해 값 1을 초래한다. 이제 MemberwiseClone() "얕은"복사본을 만들고 내 문제는 여기에 Value1 참조 유형 (AnotherClass) 속성 값이 있기 때문에 이것이 의심됩니다.
그러나 동시에 나는 또한 ICloneable을 구현하지 말 것을 말한 this site을 발견했습니다. 그래서 여기서 나의 목적을 위해 나는 무엇을해야하는지/어떤 조언을 추구 할 지 잘 모르겠다. 이것은 아마 괜찮 내 수업 직렬화가 --- (내가 직렬화에 읽을해야합니다) 할 것을 요구
public static object CloneObject(object obj)
{
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
binaryFormatter.Serialize(memStream, obj);
memStream.Seek(0, SeekOrigin.Begin);
return binaryFormatter.Deserialize(memStream);
}
}
:하지만,
여러 다른 사이트 나는 공연이 어떤 버전을 발견 ICloneable을 사용하지 않는 것에 대한 기사를 읽은 후에 ICloneable 솔루션을 추구 할 시간을 투자해야하는지 확신 할 수 없습니다.
+1 복사 생성자는 가장 간단한 방법입니다. –
+1 일반적인 질문에 대한 간단한 대답 – rro
감사합니다. 실제로 질문을하기 전에 복사 생성자를 사용해 보았습니다.하지만 지금 내 문제가 어디에 있는지를 생각합니다. 다른 인스턴스가있는 필드에 다른 복사 생성자가 필요합니다. 수업. 내가 이전에했던 (작동하지 않은) 것은 이것이었다. 다른 클래스 = other.AnotherClass. AnotherClass = new AnotherClass (other.AnotherClass), AnotherClass 자체에는 자체 복사 생성자가 있습니다. 여기서 큰소리로 생각해보십시오. 그러나 이것이 올바른 길을 추구한다는 것을 분명히 한 것에 대해 감사드립니다. 이 문제와 관련하여 Google 주변의 많은 정보가 혼란스러워졌습니다. – CptSupermrkt