Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 类的序列化';s成员_C#_Class_Serialization - Fatal编程技术网

C# 类的序列化';s成员

C# 类的序列化';s成员,c#,class,serialization,C#,Class,Serialization,请给我一些建议。我在名称空间“Xml\u form\u application”中提出了一个序列化类,它看起来是这样的: namespace Xml_form_application { public class RecordStore { public MyObject MyObjectProperty; } public class MyObject { public string item = "thing";

请给我一些建议。我在名称空间“Xml\u form\u application”中提出了一个序列化类,它看起来是这样的:

namespace Xml_form_application
{
    public class RecordStore
    {
        public MyObject MyObjectProperty;

    }

    public class MyObject
    {
        public string item = "thing";
    }
}

 //Class form2 with button2 to calling this action /serialization)
 private void button2_Click(object sender, EventArgs e)
   {
          RecordStore pd = new RecordStore();
          TextWriter tr = new StreamWriter("C:/Users/admin/Dokumenty/Visual Studio 2010/Projects/Xml_form_application/Xml_form_application/Cvicna.xml");
          XmlSerializer sr = new XmlSerializer(typeof(RecordStore));
          sr.Serialize(tr, pd);
          tr.Close();

   }
输入中有以下xml代码:

<?xml version="1.0" encoding="utf-8"?>
    <RecordStore xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

我想用xml代码输入这些内容(我如何获得这个结果):


事情
由于
pd.MyObjectProperty
的计算结果为null,因此缺少
东西
输出

默认情况下,XmlSerializer会忽略将序列化为元素的非序列类型的空值

与之相比:

RecordStore pd = new RecordStore {
    // It's really a Field, not a Property ..
    MyObjectProperty = new MyObject()
};


尽管不是必需的,但我建议始终使用
[XmlRoot]
[xmldattributes]
属性,因为它们可以减轻一些重新分解的更改。

您的
MyObjectProperty
null
,因此您不会得到这样的结果。初始化它以获得预期的结果

RecordStore pd = new RecordStore();
pd.MyObjectProperty = new MyObject();
RecordStore pd = new RecordStore();
pd.MyObjectProperty = new MyObject();