WCF DataContracts

南笙酒味 提交于 2020-01-10 10:34:09

问题


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...


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/172681/wcf-datacontracts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!