3

我正在查看 Microsoft 的 How to: 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; } }

}
4

1 回答 1

5

正如@outcoldman@EthanLi建议的那样:

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

  2. 添加一个不带参数的公共构造函数。

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

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

于 2013-04-11T04:40:44.450 回答