4

所以我试图 XML 序列化List<IObject>从接口派生的,但它们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就是我要序列化的内容。但是每次我尝试时,要么我得到一个“无法序列化接口”,但是当我实现它(无论是类IOSCMethod还是OSCMethod<T>类)时IXmlSerializable,我都会遇到“无法使用无参数构造函数序列化对象”的问题。但显然我不能,因为它是一个界面!蹩脚的裤子。

有什么想法吗?

4

1 回答 1

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;
    }
}
于 2012-10-21T17:16:37.010 回答