我正在关注微软的如何: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; } }
}
答案 0 :(得分:5)
由@outcoldman和@EthanLi建议:
将[DataContract]
属性添加到ADUser
课程。
添加公共构造函数,不带参数。
选择要通过WCF传输的字段。使用[DataMember]
属性标记所有属性。
在序列化期间,只有getter 的属性将失败:所有公开的属性都应该同时具有getter和(public!)setter 。因此,例如,如果您尝试将LoginID
属性应用于此属性,则[DataMember]
属性将失败。在这种情况下,请考虑将其更改为方法。