【问题标题】:What does it mean to put DataMemberAttribute on interface member?将 DataMemberAttribute 放在接口成员上是什么意思?
【发布时间】:2011-06-15 01:19:37
【问题描述】:

在接口成员上放置DataMemberAttribute 是什么意思? 这对派生类有何影响?

【问题讨论】:

标签: c# interface datacontract datamember


【解决方案1】:

[DataMember] 属性在应用于某个类型的成员时,指定该成员是数据协定的一部分。当此属性显式应用于字段或属性时,它指定成员值将由 DataContractSerializer 对象序列化(取自Article

【讨论】:

    【解决方案2】:

    就我而言,我将此属性与我的 WCF 服务一起使用。当我为 WCF Web 服务创建接口时,我会以这种方式定义接口:

    Imports System.ServiceModel
    <ServiceContract()>
    Public Interface IClientContract
    
        <OperationContract()>
        Function GetClientList() As IList(Of POCOClients)
    
    End Interface
    

    如您所见,该服务的客户端将收到一个 POCOCLient 类。然后我需要以这种方式使用您要求的属性来装饰 POCOClient 类,以便让该类正确序列化并通过 WCF 发送。

    <DataContract()>
    <MetadataType(GetType(POCOAuthorizedkeys.POCOAuthorizedkeysMetaData))>
    Public Class POCOAuthorizedkeys
    
        <DataMember()>
        <DisplayName("Id")>
        Public Property Id As Integer
        <DataMember()>
        <DisplayName("IdPackage")>
        Public Property IdPackage As Integer
        <DataMember()>
        <DisplayName("AuthorizedKey")>
        Public Property AuthorizedKey As String
        <DataMember()>
        <DisplayName("IdUnthrustedClient")>
        Public Property IdUnthrustedClient As Nullable(Of Integer)
    
     End Class
    

    【讨论】:

      【解决方案3】:

      如下签名所示,DataMember属性不可继承

      [AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field, Inherited = false, 
          AllowMultiple = false)]
      public sealed class DataMemberAttribute : Attribute
      

      因此,使用该属性装饰接口成员几乎没有意义,因为您也必须使用该属性装饰实现类的成员。

      【讨论】:

        猜你喜欢
        • 2014-06-02
        • 2011-04-27
        • 2013-09-25
        • 2022-05-23
        • 1970-01-01
        • 2013-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多