WCF:在未设置的情况下公开只读 DataMember 属性? [英] WCF: Exposing readonly DataMember properties without set?

查看:29
本文介绍了WCF:在未设置的情况下公开只读 DataMember 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器端类,我通过 [DataContract] 在客户端提供它.这个类有一个只读字段,我想通过属性提供它.但是,我无法这样做,因为似乎不允许我在没有 get 和 set 的情况下添加 [DataMember] 属性.

I have a server side class which I make available on the client side through a [DataContract]. This class has a readonly field which I'd like to make available through a property. However, I'm unable to do so because it doesn't seem that I'm allowed to add a [DataMember] property without having both get and set.

那么 - 有没有办法在没有 setter 的情况下拥有 [DataMember] 属性?

So - is there a way to have a [DataMember] property without setter?

[DataContract]
class SomeClass
{
    private readonly int _id; 

    public SomeClass() { .. }

    [DataMember]
    public int Id { get { return _id; } }        

    [DataMember]
    public string SomeString { get; set; }
}

或者解决方案将使用 [DataMember] 作为字段 - (例如显示 这里)?也尝试过这样做,但它似乎并不关心该字段是否为只读..?

Or will the solution be use the [DataMember] as the field - (like e.g. shown here)? Tried doing this too, but it doesn't seem to care the field is readonly..?

编辑:是通过像这样破解它来制作只读属性的唯一方法吗?(不 - 我不想这样做......)

Edit: Is the only way to make a readonly property by hacking it like this? (no - I don't want to do this...)

[DataMember]
public int Id
{
    get { return _id; }
    private set { /* NOOP */ }
}

推荐答案

您的服务器端"类实际上不会提供"给客户端.

Your "server-side" class won't be "made available" to the client, really.

会发生什么:基于数据契约,客户端将从服务的 XML 模式创建一个新的独立类.它不能使用服务器端类本身!

What happens is this: based on the data contract, the client will create a new separate class from the XML schema of the service. It cannot use the server-side class per se!

它将从 XML 模式定义重新创建一个新类,但该模式不包含任何 .NET 特定的东西,如可见性或访问修饰符 - 毕竟它只是一个 XML 模式.客户端类将以这样一种方式创建,即它在线路上具有相同的足迹" - 例如它基本上序列化为相同的 XML 格式.

It will re-create a new class from the XML schema definition, but that schema doesn't contain any of the .NET specific things like visibility or access modifiers - it's just a XML schema, after all. The client-side class will be created in such a way that it has the same "footprint" on the wire - e.g. it serializes into the same XML format, basically.

不能通过标准的基于 SOAP 的服务传输"有关该类的 .NET 特定知识 - 毕竟,您传递的只是序列化消息 - 没有课!

You cannot "transport" .NET specific know-how about the class through a standard SOAP-based service - after all, all you're passing around are serialized messages - no classes!

查看SOA 四大原则"(由微软的 Do​​n Box 定义):

Check the "Four tenets of SOA" (defined by Don Box of Microsoft):

  1. 边界是明确的
  2. 服务是自主的
  3. 服务共享架构和契约,而不是类
  4. 兼容性取决于政策

请参阅第 3 点 - 服务共享架构和契约,不是类 - 您只会共享数据契约的接口和 XML 架构 - 仅此而已 - 没有 .NET 类.

See point #3 - services share schema and contract, not class - you only ever share the interface and XML schema for the data contract - that's all - no .NET classes.

这篇关于WCF:在未设置的情况下公开只读 DataMember 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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