且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WCF数据合同

更新时间:2023-11-05 17:29:40

只要您标记了(非只读, )字段作为[DataMember],而不是属性。与XmlSerializer不同,IIRC DataContractSerializer不使用默认的ctor-它使用单独的反射机制来创建未初始化的实例。除了mono的 橄榄(WCF端口)上的所在位置



例如:



使用系统;
使用System.IO;
使用System.Runtime.Serialization;
[DataContract]
类Foo
{
[DataMember(Name = Bar)]
私有字符串栏;

公共字符串Bar {get {return bar; }}

public Foo(string bar){this.bar = bar; }
}
静态类Program
{
static void Main()
{
DataContractSerializer dcs = new DataContractSerializer(typeof(Foo));
MemoryStream ms =新的MemoryStream();
Foo orig = new Foo( abc);
dcs.WriteObject(ms,orig);
ms.Position = 0;
Foo clone =(Foo)dcs.ReadObject(ms);
Console.WriteLine(clone.Bar);
}
}


I have a WCF service hosted for internal clients - we have control of all the clients. We will therefore be using a data contracts library to negate the need for proxy generation. I would like to use some readonly properties and have some datacontracts without default constructors. Thanks for your help...

Readonly properties are fine as long as you mark the (non-readonly) field as the [DataMember], not the property. Unlike XmlSerializer, IIRC DataContractSerializer doesn't use the default ctor - it uses a separate reflection mechanism to create uninitialized instances. Except on mono's "Olive" (WCF port), where it does use the default ctor (at the moment, or at some point in the recent past).

Example:

using System;
using System.IO;
using System.Runtime.Serialization;
[DataContract]
class Foo
{
    [DataMember(Name="Bar")]
    private string bar;

    public string Bar { get { return bar; } }

    public Foo(string bar) { this.bar = bar; }
}
static class Program
{
    static void Main()
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof(Foo));
        MemoryStream ms = new MemoryStream();
        Foo orig = new Foo("abc");
        dcs.WriteObject(ms, orig);
        ms.Position = 0;
        Foo clone = (Foo)dcs.ReadObject(ms);
        Console.WriteLine(clone.Bar);
    }
}