svcutil综合类的序列化问题

时间:2010-03-17 09:11:50

标签: serialization svcutil.exe

我使用 svcutil 生成访问Web服务的类。我需要序列化它们。这个类非常简单,它的外观如下

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="cosemAttributeDescriptor", Namespace="http://www.energiened.nl/Content/Publications/dsmr/P32")]
public partial class cosemAttributeDescriptor : object, System.Runtime.Serialization.IExtensibleDataObject
{

    private System.Runtime.Serialization.ExtensionDataObject extensionDataField;

    private ushort ClassIdField;

    private string InstanceIdField;

    private sbyte AttributeIdField;

    public System.Runtime.Serialization.ExtensionDataObject ExtensionData
    {
        get
        {
            return this.extensionDataField;
        }
        set
        {
            this.extensionDataField = value;
        }
    }

    [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
    public ushort ClassId
    {
        get
        {
            return this.ClassIdField;
        }
        set
        {
            this.ClassIdField = value;
        }
    }

    [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, EmitDefaultValue=false)]
    public string InstanceId
    {
        get
        {
            return this.InstanceIdField;
        }
        set
        {
            this.InstanceIdField = value;
        }
    }

    [System.Runtime.Serialization.DataMemberAttribute(IsRequired=true, Order=2)]
    public sbyte AttributeId
    {
        get
        {
            return this.AttributeIdField;
        }
        set
        {
            this.AttributeIdField = value;
        }
    }
}

现在,问题是我无法序列化该类。这是序列化代码:

        cosemAttributeDescriptor cAttrD = new cosemAttributeDescriptor();
        cAttrD.ClassId = 3;
        cAttrD.InstanceId = "0100010800FF";
        cAttrD.AttributeId = 0;
        DataContractSerializer dSer = new DataContractSerializer(typeof(cosemAttributeDescriptor));
        StringBuilder sb = new StringBuilder();
        XmlWriter xW = XmlWriter.Create(sb);
        dSer.WriteObject(xW, cAttrD);

当我尝试序列化类时,我得到空字符串。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我发现了问题。这种方式的序列化根本不起作用,但是下面的代码具有相同的效果。

DataContractSerializer dSer = new DataContractSerializer(typeof(cosemAttributeDescriptor));
MemoryStream mStr = new MemoryStream(); 
dSer.WriteObject(mStr, cAttrD); 
mStr.Position = 0; 
StreamReader sRead = new StreamReader(mStr); 
String result = sRead.ReadToEnd();