将DataMemberAttribute放在接口成员上意味着什么?

时间:2011-01-25 08:48:26

标签: c# interface datacontract datamember

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

3 个答案:

答案 0 :(得分:10)

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

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

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

答案 1 :(得分:1)

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

Imports System.ServiceModel
<ServiceContract()>
Public Interface IClientContract

    <OperationContract()>
    Function GetClientList() As IList(Of POCOClients)

End Interface

如您所见,此服务的客户将收到POCOCLient类。然后我需要用这种方式用你要求表单的属性来装饰POCOClient类,以便让类正确地序列化并发送víaWCF。

<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

答案 2 :(得分:-1)

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