DataContractAttribute的基础知识

时间:2013-04-10 22:00:33

标签: c# wcf datacontractserializer datacontract

我正在关注微软的如何:Create a Basic Data Contract for a Class or Structure,但它给我留下了很多问题。

他们提供了这个非常简单的例子:

using System;
using System.Runtime.Serialization;

[DataContract]
public class Person
{
  // This member is serialized.
  [DataMember]
  internal string FullName;

  // This is serialized even though it is private.
  [DataMember]
  private int Age;

  // This is not serialized because the DataMemberAttribute 
  // has not been applied.
  private string MailingAddress;

  // This is not serialized, but the property is.
  private string telephoneNumberValue;

  [DataMember]
  public string TelephoneNumber
  {
    get { return telephoneNumberValue; }
    set { telephoneNumberValue = value; }
  }
}

就我而言,我还需要包含另一个名为ADUser的自定义类对象(Active Directory用户)。

我了解ADUser必须标有DataContractAttribute,但我不明白该怎么做。

这是Microsoft的课程,但这次添加了ADUser字段:

using System;
using System.Runtime.Serialization;

[DataContract]
public class Person
{
  // This member is serialized.
  [DataMember]
  internal string FullName;

  // This is serialized even though it is private.
  [DataMember]
  private int Age;

  // This is not serialized because the DataMemberAttribute 
  // has not been applied.
  private string MailingAddress;

  // This is not serialized, but the property is.
  private string telephoneNumberValue;

  [DataMember]
  public string TelephoneNumber
  {
    get { return telephoneNumberValue; }
    set { telephoneNumberValue = value; }
  }

  [DataMember]
  public ADUser UserInfo { get; set; }

}

我真的不明白我的ADUser课程需要做什么或有什么需要做,但我确信private的内容可以不受影响。

我如何修复这个ADUser类示例?

public class ADUser
{

  private string first, last, loginID;

  public ADUser() {
    first = null;
    last = null;
    loginID = null;
  }

  private void getInfo() {
    // code goes here
    // which sets loginID;
  }

  public void SetName(string first, string last) {
    this.first = first;
    this.last = last;
    getInfo();
  }

  public string LoginID { get { return loginID; } }

}

1 个答案:

答案 0 :(得分:5)

@outcoldman@EthanLi建议:

  1. [DataContract]属性添加到ADUser课程。

  2. 添加公共构造函数,不带参数。

  3. 选择要通过WCF传输的字段。使用[DataMember]属性标记所有属性。

  4. 在序列化期间,只有getter 的属性将失败:所有公开的属性都应该同时具有getter和(public!)setter 。因此,例如,如果您尝试将LoginID属性应用于此属性,则[DataMember]属性将失败。在这种情况下,请考虑将其更改为方法。