我正在尝试序列化包含接口的对象。但是,接口不能序列化。通常,我会使用NonSerialized
标签之类的东西,但我不知道如何将此属性应用于我无法修改的类,例如预定义的 .NET 类之一(例如:)System.Diagnostics.Process
。
例如,考虑以下代码:
using System.Diagnostics
using System.Xml.Serialization;
class Program
{
static void Main(string[] args)
{
try
{
XmlSerializer x = new XmlSerializer(typeof(Process));
}
catch (Exception e)
{
Console.WriteLine(e.InnerException.InnerException.Message);
}
}
}
这将打印以下结果:
Cannot serialize member System.ComponentModel.Component.Site of type System.ComponentModel.ISite because it is an interface.
有没有办法在我无法修改的类中执行以下任何操作,例如系统类?
- 在序列化过程中选择性地忽略子元素,这样子元素根本不会被序列化
- 用完成相同事情的东西标记一个元素
NonSerialized
I've thought of some solutions like using reflection to dynamically generate a class that contains all the same members as the class to be serialized, doing some type of deep copy, and serializing that. However, I'm curious to see if there is any simpler way to accomplish this serialization task other than going the class generating reflection route.