为什么性能没有二传手没有序列号序列号、性能、二传

2023-09-02 11:47:23 作者:傲娇小仙女

我有一个序列化的类,在我的类中的属性之一生成一个的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.

另外,您可以切换到使用DataContractSerializer,它更灵活。

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