C# DataContractAttribute的基础知识
我正在看微软的《如何:》,但它给我留下了很多问题 他们提供了一个非常简单的例子:C# DataContractAttribute的基础知识,c#,wcf,datacontractserializer,datacontract,C#,Wcf,Datacontractserializer,Datacontract,我正在看微软的《如何:》,但它给我留下了很多问题 他们提供了一个非常简单的例子: 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 pri
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
标记,但我不知道具体如何操作
这是微软的课程,但这次添加了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; } }
}
正如所建议的那样:
[DataContract]
属性添加到ADUser
类中[DataMember]
属性标记所有这些属性[DataMember]
属性应用于LoginID
属性,则该属性将失败。在这种情况下,考虑将其改为方法。您是否尝试将
DataMember
放入AdUser
中的每个字段,并用DataContract
标记AdUser
?正如@outcoldman所说,只需要对AdUser执行相同的操作。基本上,DataContact中的每个DataMember都需要是可序列化的,这意味着,如果有一个类,它需要是DataContact作为weel。另外,需要确保类有一个不需要参数的构造函数。那么简单吗?好的!:)Microsoft自动创建的某些东西具有[ServiceContract]
和[OperationContract]
成员以及相应的[DataContract]
。如果我的ADUser
不是一项服务,我是否也需要包括其中的任何一项?[ServiceContract]是您的服务,[OperationContract]-您的方法此答案不太正确。第2步是不必要的。在步骤4(不是真正的步骤,但无论如何)中,getter和setter都不需要是public
。当使用DataContractSerializer
(与WCF一样)时,可访问性将被忽略(public
vsprivate
),并且序列化程序在反序列化时不使用任何构造函数,因此无参数构造函数是否存在并不重要。请注意,这与其他序列化程序不同,例如XmlSerializer
。