在具有 DataMember 属性的 GetHashCode 中使用 Non-Readonly 属性

Use Non-Readonly property in GetHashCode with DataMember attribute

我使用 DataContract 来处理 WCF 服务中的 class。因此,我需要 属性 ApiCallStatus(类型:ApiCallStatus 作为枚举)来同时具有自动 getter 和 -setter。但是对于 GetHashCode 的覆盖,我需要一个 "readonly" 属性 来正确实现它。有没有一种方法可以使这两个要求都能正常工作并以干净的方式实现?

[DataContract]
public class ApiCallStatusInformation {
    [DataMember]
    public ApiCallStatus ApiCallStatus { get; set; }

    public bool Equals(ApiCallStatusInformation other) {
        if (ReferenceEquals(null, other))
            return false;
        if (ReferenceEquals(this, other))
            return true;

        return this.ApiCallStatus == other.ApiCallStatus;
    }

    public override bool Equals(object obj) {
        if (ReferenceEquals(null, obj))
            return false;
        if (ReferenceEquals(this, obj))
            return true;
        return obj.GetType() == this.GetType() && this.Equals((ApiCallStatusInformation) obj);
    }

    public override int GetHashCode() {
        return (int) this.ApiCallStatus;
    }
}

一个[DataMember]可能是private readonly,这样就避免了这个问题。

之所以可以是private readonly是因为[DataContract]实现使用了反射来设置[DataMember]字段,也就是说privatereadonly 方面被忽略。