gpt4 book ai didi

c# - 数据契约(Contract)异常。无法序列化

转载 作者:IT王子 更新时间:2023-10-29 03:48:48 25 4
gpt4 key购买 nike

我有以下 WCF 数据契约(Contract):

[DataContract]
public class Occupant
{
private string _Name;
private string _Email;
private string _Organization;
private string _Badge;

public Occupant(string name, string badge, string organization)
{
Name = name;
Badge = badge;
Organization = organization;
}

public Occupant(string name, string badge)
{
Value = name;
Key = badge;
}

[DataMember]
public string Key
{
get { return _Name; }
set { _Name = value; }
}

[DataMember]
public string Value
{
get { return _Badge; }
set { _Badge = value; }
}

[DataMember]
public string Name
{
get { return _Name; }
set { _Name = value; }
}

[DataMember]
public string Email
{
get { return _Email; }
set { _Email = value; }
}

[DataMember]
public string Organization
{
get { return _Organization; }
set { _Organization = value; }
}

[DataMember]
public string Badge
{
get { return _Badge; }
set { _Badge = value; }
}
}

当我尝试通过 Web 浏览器访问此服务(它托管在 IIS 上)时,出现此错误:

System.Runtime.Serialization.InvalidDataContractException: Type 'MyNamespace.Occupant' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute.

我的方法之一是返回 Occupant 类型的 List。这会导致它吗?

最佳答案

因为您已经提供了一个或多个初始化构造函数,您还需要添加一个无参数(默认)构造函数。

即您需要添加:

[DataContract]
public class Occupant
{
// *** Needed only for Serialization
public Occupant() {}
...

这是因为 default constructor disappears当您添加显式构造函数时。

[问题不在于返回 List<Occupant> 的方法,因为方法没有序列化)。]

关于c# - 数据契约(Contract)异常。无法序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10077121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com