XML Serialize从接口派生的通用对象列表,,,

时间:2012-09-17 13:29:49

标签: c# xml generics serialization interface

所以我正在尝试对来自界面的List<IObject>进行XML序列化,但IObjects是通用类型...最好的代码:

public interface IOSCMethod
{
    string Name { get; }
    object Value { get; set; }
    Type Type { get; }
}

public class OSCMethod<T> : IOSCMethod
{
    public string Name { get; set; }
    public T Value { get; set; }
    public Type Type { get { return _type; } }

    protected string _name;
    protected Type _type;

    public OSCMethod() { }

    // Explicit implementation of IFormField.Value
    object IOSCMethod.Value
    {
        get { return this.Value; }
        set { this.Value = (T)value; }
    }
}

我有一份IOSCMethods:

List<IOSCMethod>

我以下列方式添加对象:

        List<IOSCMethod> methodList = new List<IOSCMethod>();
        methodList.Add(new OSCMethod<float>() { Name = "/1/button1", Value = 0 });
        methodList.Add(new OSCMethod<float[]>() { Name = "/1/array1", Value = new float[10] });

这就是 methodList 这就是我要序列化的内容。但每次我尝试时,要么我得到一个“无法序列化一个接口”但是当我创建它时(IOSCMethodOSCMethod<T>类)实现IXmlSerializable我得到的问题是“无法使用无参数构造函数序列化对象。但显然我不能,因为它是一个界面!跛脚裤。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这就是你想要的:

[TestFixture]
public class SerializeOscTest
{
    [Test]
    public void SerializeEmpTest()
    {
        var oscMethods = new List<OscMethod>
                             {
                                  new OscMethod<float> {Value = 0f}, 
                                  new OscMethod<float[]> {Value = new float[] {10,0}}
                              };
        string xmlString = oscMethods.GetXmlString();
    }
}

public class OscMethod<T> : OscMethod
{
    public T Value { get; set; }
}

[XmlInclude(typeof(OscMethod<float>)),XmlInclude(typeof(OscMethod<float[]>))]
public abstract class OscMethod
{

}

public static class Extenstion
{
    public static string GetXmlString<T>(this T objectToSerialize)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());
        StringBuilder stringBuilder = new StringBuilder();
        string xml;
        using (var xmlTextWriter = new XmlTextWriter(new StringWriter(stringBuilder)))
        {
            xmlSerializer.Serialize(xmlTextWriter, objectToSerialize);
            xml = stringBuilder.ToString();
        }
        return xml;
    }
}