我已經能夠使用ShouldSerialize 屬性模式與XmlSerializer
忽略ICollection<>
類型的屬性。以下是示例代碼。如果我在ListOfTestClassB
屬性上使用XmlIgnore
,但我希望使用ShouldSerialize
模式實現相同的功能,則該模式有效。如果我運行下面的代碼,我得到「System.InvalidOperationException」曰:無法使ShouldSerialize模式與XmlSerializer一起使用
無法序列類型System.Collections.Generic.ICollection`1成員ConsoleApplication3.TestClassA.ListOfTestClassB [ConsoleApplication3.TestClassB,ConsoleApplication3,版本= 1.0.0.0,Culture = neutral,PublicKeyToken = null]],因爲它是一個接口。
任何人都可以突出顯示我錯過了什麼?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication3
{
[Serializable]
public class TestClassA
{
public int A { get; set; }
public int B { get; set; }
public string C { get; set; }
public TestClassB TestClass { get; set; }
public virtual ICollection<TestClassB> ListOfTestClassB { get; set; }
public bool ShouldSerializeListOfTestClassB()
{
return false;
}
}
[Serializable]
public class TestClassB
{
public int Int32 { get; set; }
public string String { get; set; }
}
class Program
{
static object GetObject()
{
return new TestClassA { A = 1, B = 2, C = "test class a", TestClass = new TestClassB { Int32 = 11, String = "test class b"} };
}
static void Main(string[] args)
{
var result = new StringBuilder();
var entity = GetObject();
var ser = new XmlSerializer(entity.GetType());
var settings = new XmlWriterSettings { OmitXmlDeclaration = true };
using (var stream = new MemoryStream())
{
// make a copy of the entity - we do not want to serialize ZIP file !
var formatter = new BinaryFormatter();
formatter.Serialize(stream, entity);
stream.Position = 0;
entity = formatter.Deserialize(stream);
}
// serialize object
ser.Serialize(XmlWriter.Create(result, settings), entity);
Console.WriteLine(result.ToString());
Console.ReadLine();
}
}
}
該序列化程序需要被緩存,例如在靜態哈希表中,以避免嚴重的內存泄漏。請參閱[XmlSerializer類:動態生成的程序集](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx) – dbc
謝謝@dbc。我編輯了我的答案,以引起關注。 – Amy
謝謝@Amy這看起來很有希望。我遇到了XmlAttributedOverride的使用,但ShouldSerialize patter似乎是一個簡單的實現,並提供了更多的控制,但顯然我不能使用它。我會用你的建議。非常感謝! – shigarr