【问题标题】:What's wrong with Property without set?没有设置的属性有什么问题?
【发布时间】:2015-05-19 08:01:20
【问题描述】:

我有一个用于 WCF 服务的类。

接口定义

[WebGet(ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "GetMyStuff/?p={param}",
        BodyStyle = WebMessageBodyStyle.Bare)]
MyResponseObject MyMethod(string param);

在我拥有的属性中

public bool IsDecorated {
  get {
    return !String.IsNullOrEmpty(Decoration);
  }
}

导致请求被拒绝加载。

添加后

set { }

成功了。

有什么线索吗?

【问题讨论】:

  • 只读属性未序列化。因为当它们被反序列化时,它们将没有 setter。读这个。 stackoverflow.com/questions/13401192/…
  • set{} 不会使其成为非只读
  • 编译器不关心你是否在里面写了逻辑。它只关心你的属性应该有一个 setter。

标签: c# wcf serialization properties datacontract


【解决方案1】:

只读属性未序列化。因为当它们被反序列化时,它们将没有 setter。为了避免这个问题,只读属性一开始就没有序列化。

setprivate 类似

public List<Foo> Bar {get; private set;}`.

阅读
Why are properties without a setter not serialized
Force XML serialization to serialize readonly property
Why isn't my public property serialized by the XmlSerializer?

编译器不关心你是否在 setter 中编写了逻辑。它只关心你的属性应该有一个 setter。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多