类型不可序列化,因为它不是公共的? [英] Type is not serializable because it's not public?

查看:28
本文介绍了类型不可序列化,因为它不是公共的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无法正确序列化的公共类.尝试时,抛出以下异常:

I have a public class that won't serialize properly. When attempted, the following exception is thrown:

数据协定类型MyProject.MyClass"不可序列化,因为它不是公开的.公开类型将修复此错误.或者,您可以将其设为内部,并在程序集上使用 InternalsVisibleToAttribute 属性以启用内部成员的序列化 - 有关更多详细信息,请参阅文档.请注意,这样做会带来一定的安全隐患.

The data contract type 'MyProject.MyClass' is not serializable because it is not public. Making the type public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.

我的课程公开的:

[DataContract]
public class MyClass
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    private int Count;

    public MyClass()
    {
        Name = string.Empty;
        Count = 0;
    }
}

当课程明显是公开的时,为什么我会收到此异常?

Why am I getting this exception when the class is clearly public?

推荐答案

在 Windows Phone 7 应用中,您不能序列化私有成员:

In Windows Phone 7 apps, you can't serialize private members:

好吧,碰巧 WP7 应用程序在部分信任"环境中运行,并且在完全信任"环境之外,DataContractSerializer 拒绝序列化或反序列化非公共成员.当然,这个例外被 .NET 内部吞并了,所以我所看到的只是关于我确定是公开的事情的奇怪信息不公开".我将我正在序列化的所有私有字段更改为公共字段,一切正常.http://geekswithblogs.net/mikebmcl/archive/2010/12/29/datacontractserializer-type-is-not-serializable-because-it-is-not-public.aspx

Well, it just so happens that WP7 apps run in a "partial trust" environment and outside of "full trust"-land, DataContractSerializer refuses to serialize or deserialize non-public members. Of course that exception was swallowed up internally by .NET so all I ever saw was that bizarre message about things that I knew for certain were public being "not public". I changed all the private fields I was serializing to public and everything worked just fine. http://geekswithblogs.net/mikebmcl/archive/2010/12/29/datacontractserializer-type-is-not-serializable-because-it-is-not-public.aspx

更改代码以避免序列化私有成员可解决此问题.

Changing the code to avoid serializing private members fixes the issue.

这篇关于类型不可序列化,因为它不是公共的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆