只读属性的 WCF DataContract 序列化? [英] WCF DataContract serialization of read-only properties?

查看:38
本文介绍了只读属性的 WCF DataContract 序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我使用 WCF 时,我总是尝试创建最终通过网络连接的不可变类(即在构造函数中设置的参数,属性是只读的).然而,这妨碍了 WCF 序列化,它要求所有属性都是 Public get/set(这是有道理的,因为它必须反序列化它们)

Whenever I use WCF, I always try to make immutable classes that end up going over the wire (i.e. parameters set in constructor, properties are read-only). However, this gets in the way of WCF serialization, which demands that all properties be Public get/set (which makes sense, because it has to deserialize them)

即使在这篇相关帖子中,我也看到他们的解决方案最终将所有内容公之于众,这违反了我的良好编程意识.有没有办法解决?我是否必须满足于这个解决方案或诸如冰棒不变性之类的东西并对此感到满意?

Even in this related post, I see that their solution ended up making everything Public, which violates my sense of good programming. Is there any way around this? Do I have to just settle for this solution or something like popsicle immutability and be happy with it?

我尝试的另一件事是这样的,我有一个用于所有内容的基类和一个使集合无用的派生类:

The other thing I tried was something like this, where I'd have a base class for everything and a derived class that made the set useless:

/// <summary>
/// This represents a discovered virtual-machine template that can be
/// instantiated into a RunningVirtualMachine
/// </summary>
[DataContract]
[XmlRoot("VMTemplate")]
public class VirtualMachineTemplateBase
{
    [DataMember]
    public virtual ulong SizeInBytes { get; set; }
}

/// <summary>
/// This class is the real guts of VirtualMachineTemplate that we're hiding
/// from the base class.
/// </summary>
[XmlInclude(typeof(VirtualMachineTemplateBase))]
public class VirtualMachineTemplate : VirtualMachineTemplateBase, IXmlPicklable, IEnableLogger
{
    ulong _SizeInBytes;
    public override ulong SizeInBytes {
        get { return _SizeInBytes; }
        set { }
    }
}

推荐答案

如果您使用 DataContractSerializer(这是 WCF 的默认设置),您可以序列化使用 [DataMember] 属性修饰的任何hting- 甚至是只读字段:

If you use the DataContractSerializer (which is the default for WCF), you can serialize anyhting that's decorated with the [DataMember] attribute - even a read-only field:

[DataContract]
public class VirtualMachineTemplate : VirtualMachineTemplateBase, IXmlPicklable, IEnableLogger
{
    [DataMember]
    ulong _SizeInBytes;
}

但是您需要使用 DataContractSerializer - 而不是 XML 序列化器.XML 序列化器只能序列化公共属性(它会,除非您在它们上放置 [XmlIgnore]).

But you need to use the DataContractSerializer - not the XML serializer. The XML serializer can ONLY serialize public properties (and it will, unless you put a [XmlIgnore] on them).

DataContractSerializer 不同:

The DataContractSerializer is different:

  • 它不需要无参数的默认构造函数
  • 它会序列化您用[DataMember]
  • 明确标记的内容
  • 但这可以是任何东西 - 一个字段、一个属性和任何可见性(私有、受保护、公共)
  • 它比 XmlSerializer 快一点,但您无法控制 XML 的形状 - 您只能对包含的内容有发言权

见这个博客文章 和这个 博文 了解更多提示和技巧.

See this blog post and this blog post for a few more tips and tricks.

马克

这篇关于只读属性的 WCF DataContract 序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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