首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DataContractAttribute基础

DataContractAttribute基础
EN

Stack Overflow用户
提问于 2013-04-10 22:00:33
回答 1查看 13.9K关注 0票数 3

我正在看微软的“如何:为类或结构创建基本数据契约”,但它给我留下了很多问题。

它们提供了一个非常简单的例子:

代码语言:javascript
复制
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用户)的自定义类对象。

我知道ADUser必须用DataContractAttribute标记,但我不知道如何才能做到这一点。

下面是微软的类,但是这次添加了ADUser字段:

代码语言:javascript
复制
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类示例?

代码语言:javascript
复制
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; } }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-11 04:40:44

正如@outcoldman@EthanLi所建议的:

  1. [DataContract]属性添加到ADUser类。
  2. 添加没有参数的公共构造函数。
  3. 选择要通过WCF的字段。使用[DataMember]属性标记所有这些属性。
  4. 只有getter的属性将在序列化期间失败:所有公开的属性都应该同时具有getter和(public!)赛特。因此,例如,如果您尝试将[DataMember]属性应用于它,那么您的[DataMember]属性将失败。在这种情况下,考虑将其更改为方法。
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15937252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档