深度 xml 序列化一个结构体选项 [英] Deep xml serialize a struct Options

查看:28
本文介绍了深度 xml 序列化一个结构体选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下所示的类和结构.如果我将类序列化为正在使用 xmlserializer 我得到:

I have the class and struct shown below. If I serialize the class as is using xmlserializer I get:

<测试>
<TestNumber1 >5
<内部测试/>
</测试>

< Test>
< TestNumber1 >5< /TestNumber1 >
< InnerTest / >
< /Test >

使 InnerTest 正确序列化的最简单方法是什么(最好使用 xmlserializer)而不给 Number 属性一个二传手?

what is the easiest way to make InnerTest serialise properly (preferably using xmlserializer) with out giving the Number property a setter?

谢谢,尼克

public class Test 
{ 
    private InnerTest innerTest; 
    private int testNumber; 


    public Test() 
    { 
        this.innerTest = new InnerTest(); 
        this.testNumber = 5; 
    } 


    public int TestNumber1 
    { 
        get { return this.testNumber; } 
        set { this.testNumber = value;} 
    } 


    public InnerTest InnerTest 
    { 
        get { return this.innerTest; } 
        set { this.innerTest = value;} 
    } 


} 


public struct InnerTest 
{ 
    private int number; 


    public InnerTest(int number) 
    { 
        this.number = number; 
    } 
    public int Number{get { return number; }} 
} 

推荐答案

如果在这种情况下可能,我会使用 DataContractSerializer (.NET 3.0),我会使用类似的东西:

If possible in this scenario, I would use DataContractSerializer (.NET 3.0), and I would use something like:

[DataMember]
public int TestNumber1 
{ 
    get { return this.testNumber; } 
    set { this.testNumber = value;} 
} 

// note **not** a data-member
public InnerTest InnerTest 
{ 
    get { return this.innerTest; } 
    set { this.innerTest = value;} 
} 

[DataMember]
private int InnerTestValue
{
    get {return innerTest.Number;}
    set {innerTest = new InnerTest(value);}
}

因此回避了这个问题.您可以使用 XmlSerializer 做类似的事情,但是您需要将 InnerTestValue 设为公开(尽管您可以使用 [Browsable(false), EditorBrowsable(EditorBrowsableState.从不)] - 但这并不理想).

thus side-stepping the issue. You can do similar with XmlSerializer, but you'd need to make InnerTestValue public (although you could decorate it with [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - but this isn't ideal).

当然,如果结构上有多个值......更棘手.当然,您可以拥有多个 shim 属性,但这有点麻烦.基本上,[反]序列化和不可变对象(结构应该如此)不能很好地混合在一起.

Of course, if you have multiple values on the struct... trickier. You can have multiple shim properties, of course, but that is a bit scrappy. Basically, [de]serialization and immutable objects (as structs should be) don't mix all that well.

另一种选择是维护一个单独的 POCO 版本,该版本始终使用可变类,并在两者之间进行转换;同样,作为大型对象模型的选项不是很有吸引力.

Another option is to maintain a separate POCO version that uses mutable classes throughout, and translate between the two; again, not very attractive as an option for large object models.

这篇关于深度 xml 序列化一个结构体选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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