객체를 직렬화 한 후 빈 xmlfile을 얻습니다. 저는 Monodevelop과 Unity 4를 사용하고 있습니다. 주로이 커뮤니티에서 오랜 시간 동안 검색했지만 더 어려운 답변으로 어려운 문제 만 발견했습니다. :) 제 생각에는 너무 간단하다고 생각합니다. 제발 도와주세요. (저는 c #을 처음 사용합니다) 직렬화 된 개체는 다음과 같습니다.
[System.Serializable]
public class information {
private string data1;
private string data2;
private string data3;
public void Data1(string text)
{
data1 = text;
}
public string GetData1 ()
{
return data1;
}
public void Data2(string text)
{
data2 = text;
}
public string GetData2 ()
{
return data2;
}
public void Data3(string text)
{
data3 = text;
}
}
직렬화 클래스는 다음과 같습니다. 여기에 문제가있을 수 있습니다.
public class SaveXml {
public void SaveData(object obj, string filename)
{
XmlSerializer sr = new XmlSerializer(obj.GetType());
TextWriter writer = new StreamWriter(filename);
sr.Serialize(writer, obj);
writer.Close();
}
public string Load()
{
if(File.Exists("accdata.xml"))
{
XmlSerializer xs = new XmlSerializer(typeof(information));
FileStream read = new FileStream("accdata.xml",FileMode.Open, FileAccess.Read, FileShare.Read);
information info = (information)xs.Deserialize(read);
return info.GetData1();
}
else
{
return "file does not exist";
}
}
직렬화 및 직렬화 된 객체는 다음 두 개의 버튼이있는 메뉴에 의해 호출됩니다.
if(GUI.Button(new Rect(10,50,300,100),"Save"))
{
SaveXml saver = new SaveXml();
information infol = new information();
infol.Data1("textone");
infol.Data2("texttwo");
infol.Data3( "textthree");
saver.SaveData(infol, "accdata.xml");
}
if(GUI.Button(new Rect(500,50,300,100),"Load"))
{
SaveXml saver1 = new SaveXml();
text = saver1.Load();
}
따라서 클래스 메뉴에 선언 된 변수 텍스트는 저장 버튼과 LoadButton을 클릭 한 후 "textone"이어야합니다. 저장 버튼은 비어있는 파일을 만듭니다.
The Deserialization seems to work but of course there is no String in the data1 variable in Information so the variable in the menu called text is empty too. I get no errors and i can work with the object after serialization. So why doesnt my serialization work? Please help me. I excuse for my bad english and mistakes, i am new to stackoverflow.
Xml serializer serializes public fields/properties not methods. Change your methods to properties. For ex,
public string Data2
{
set { data2 = value; }
get { return data2; }
}
So your information
class can be
public class Information
{
public string Data1 { get; set; }
public string Data2 { get; set; }
public string Data3 { get; set; }
}
BTW: you don't need this Serializable
attribute. It is only used by BinaryFormatter
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다