4

だから私は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これが私が連載しようとしているものです。しかし、私が試みるたびに、「インターフェイスをシリアル化できません」というメッセージが表示されますが、それを (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 に答える