Using Structs with WCF Services

前端 未结 1 1901
旧巷少年郎
旧巷少年郎 2021-01-17 09:32

Is there any official recommendation on using structs as return types with WCF services?

I\'m currently interacting with a service I did not write

相关标签:
1条回答
  • 2021-01-17 10:16

    If you can create a struct and put a [DataContract] attribute on it - go ahead and use it! To WCF, that doesn't make a difference - WCF only requires that the class or struct in use by marked with a DataContract attribute and all the fields to be included in the serialized message are to be marked with a [DataMember] attribute.

    If you check the MSDN docs on the DataContractAttribute, it shows that you can use it on a struct as well:

    [AttributeUsageAttribute(AttributeTargets.Class|
     AttributeTargets.Struct|AttributeTargets.Enum, 
     Inherited = false, AllowMultiple = false)]
    public sealed class DataContractAttribute : Attribute
    

    UPDATE: as for when to use a struct instead of a class (in general, in .NET), see this SO question here:

    When should I use a struct instead of a class?

    However, since WCF is really about message passing (i.e. your client makes a method call, that call and its parameters get converted into a serialized message that gets sent across the wire and then re-assembled on the other end and turned back into a method call), I don't see any compelling reason to ever use a struct.

    All the benefits of general .NET don't really apply in the SOA-world of WCF, I would say (you're not passing around class or struct instances - see above).

    0 讨论(0)
提交回复
热议问题