首页 文章

具有只读属性的WCF DataContract

提问于
浏览
14

我正在尝试从WCF中的服务方法返回一个复杂类型 . 我正在使用C#和.NET 4.这种复杂类型意味着不变(与.net字符串相同) . 此外,服务只返回它,并且从不接收它作为参数 .

如果我尝试仅在属性上定义getter,则会出现运行时错误 . 我想这是因为没有setter导致序列化失败 . 不过,我认为这种类型应该是不变的 .

例:

[DataContract]
class A 
{
   [DataMember]
   int ReadOnlyProperty {get; private set;}
}

由于序列化问题,服务无法加载 .

Is there a way to make readonly properties on a WCF DataContract? Perhaps by replacing the serializer? If so, how? If not, what would you suggest for this problem?

谢谢,
阿萨夫

8 回答

  • 14

    DataMember字段不能只读,因为wcf不按原样序列化对象,并且每次反序列化开始时都会使用默认构造函数创建新的对象实例 . Dissechers在反序列化后使用setter设置字段值 .

    但所有上层文字都可能是一个大错误:)

    要使它们真正只读,请创建服务器逻辑,验证thiss字段值 .

  • 0

    [DataMember] 放在支持领域,你不需要一个二传手 .

  • 1

    让你的setter公开以满足序列化程序,但只是不对setter做任何事情 . 不是'纯粹',而是完成它

    public string MyProperty 
    {
        get {
            return this._myProperty
        }
        set {}
    }
    
  • 8

    您不能只读取属性,但是通过使字段成为 Contract 的一部分而不是属性,您可以接近只读:

    [DataContract]
    public class A 
    {
       public class A(){}
       public class A(int readonlyproperty){ _readonlyproperty = readonlyproperty}
    
       [DataMember(Name = "ReadOnlyProperty")]
       internal int _readonlyproperty;
    
       public int ReadOnlyProperty {
          get {return _readonlyproperty;}
          private set {_readonlyproperty = value;}
    }
    

    接下来让你的内部可以在wcf中访问:

    [assembly: InternalsVisibleTo("System.Runtime.Serialization")]
    

    有关如何使用此优势的一些示例:wcf-and-datacontract-serialization-internals-and-tips

  • 0

    像其他人所说的那样,WCF需要吸气剂和制定者 . 话虽这么说,我带着同样的问题来到这里,答案让我问为什么我需要一个只读属性 . 如果使用MVVM模式,则服务返回的类是Model,因此不应直接由UI公开 . 您可以轻松地将ViewModel设置为只读 . 或者,您可以使用非UI目标的Facade类 .

  • -1

    实际上,您可以使只读字段可序列化 . 在构造DataContractSerializer时,需要将DataContractSerializerSettings的'SerializeReadOnlyTypes'属性设置为'True',如下所示:

    var xmlSerializer = new DataContractSerializer(typeof(yourTypeHere),  new DataContractSerializerSettings {SerializeReadOnlyTypes=true});
    

    请参阅MSDN说明和详细信息,此处:https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializersettings(v=vs.110).aspx

  • 0

    WCF需要能够序列化/反序列化属性,而私有属性是不可能的 . 要具有只读属性(在复杂类型中):

    • 将类装饰为[DataContract(IsReference = true)]

    • 将每个/属性装饰为[DataMember]

    • Public Get, Internal Set

    [DataContract(IsReference = true)]
        public class Format : ValueObject<Format>
        {
            [DataMember]
            public int Height { get; internal set; }
        }
    
  • 3

    你试过让setter私有吗?

    就像是:

    public string MyProperty
    {
    get;
    private set;
    }
    

相关问题