为什么性能没有二传手没有序列号 [英] Why are properties without a setter not serialized

查看:158
本文介绍了为什么性能没有二传手没有序列号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个序列化的类,在我的类中的属性之一生成一个的Guid 的吸气剂。该物业没有实现setter和是序列化过程中忽略。这是为什么?我总是要实现秩序制定者我的财产被序列化。

I have a serializable class and one of the properties in my class generates a Guid in the getter. The property implements no setter and is ignores during serialization. Why is that and do I always have to implement a setter in order for my property to be serialized.

[Serializable]
public class Example
{
    [XmlAttribute("id")]
    public string Id
    {
        get
        {
             return Guid.NewGuid().ToString();
        }
    }
}

我想实现一个空的setter和它得到正确的序列化。

I tried implementing an empty setter and it got serialized correctly.

[Serializable]
public class Example
{
    [XmlAttribute("id")]
    public string Id
    {
        get
        {
             return Guid.NewGuid().ToString();
        }
        set {}
    }
}

更新

您可以指出我应该如何定义的属性,其值永远不会改变,或那些对内部产生的价值?

Can you point out how should I define properties whose values never change or ones that the value for is generated internally?

推荐答案

这是的XmlSerializer 的限制,它不序列只读属性,你在做你的第二个例子是本质上是黑客得到它的序列化,但是,它是无用的,如果你需要它之​​后反序列化。

It's a limitation of XmlSerializer it doesn't serialize read-only properties, what you have done in your second example is essentially the hack to get it to serialize, however, it's useless if you need it to deserialize later.

另外,您可以切换到使用<一个href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx">DataContractSerializer,它更灵活。

Alternatively you could switch to using DataContractSerializer, it's more flexible.

这篇关于为什么性能没有二传手没有序列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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