WCF数据合同 [英] WCF DataContracts

查看:97
本文介绍了WCF数据合同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为内部客户端托管了WCF服务-我们可以控制所有客户端。因此,我们将使用数据合同库来消除对代理生成的需求。我想使用一些只读属性,并具有一些没有默认构造函数的数据契约。
感谢您的帮助...

解决方案

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



例如:



<$使用默认的ctor(当前或最近的某个时间)。 p $ p> 使用系统;
使用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);
    }
}

这篇关于WCF数据合同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆