本文介绍了Datacontract例外。不能序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下datacontract:

I have the following datacontract:

[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),我收到此错误:

When I try to access this service via web browser (it is hosted on IIS), I am getting this error:

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.

我的一个方法返回一个列表类型乘员。这将是造成的呢?

One of my methods is returning a List of type Occupant. Would this be causing it?

推荐答案

由于您提供一个或多个构造函数初始化,你还需要增加一个无参数(缺省)构造函数。

Because you have provided one or more initializing constructors, you will also need to add a parameterless (default) constructor.

即。您需要添加:

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

这是因为default构造消失当您添加明确的构造函数。

This is because the default constructor disappears when you add an explicit constructor.

[问题不在于方法返回名单,其中,乘员GT; ,因为方法不序列化)]

[The issue isn't with the method returning List<Occupant>, since methods aren't serialized).]

这篇关于Datacontract例外。不能序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 15:58