2011-03-29 68 views
6

我想序列化一个嵌套类的对象。我已标记的与[非序列化]属性的嵌套类,但是我收到一个错误:非序列化属性创建错误

Attribute 'NonSerialized' is not valid on this declaration type. It is only valid on 'field' declarations.

如何省略嵌套类从序列化?

我已经包含了一些代码,可以显示我正在尝试做什么。 感谢您的帮助。

[Serializable] 
public class A_Class 
{ 
    public String text { get; set; } 

    public int number { get; set; } 
} 

[Serializable] 
public class B_Class 
{ 
    [NonSerialized] 
    public A_Class A { get; set; } 

    public int ID { get; set; } 
} 

public byte[] ObjectToByteArray(object _Object) 
{ 
    using (var stream = new MemoryStream()) 
    { 
     var formatter = new BinaryFormatter(); 
     formatter.Serialize(stream, _Object); 
     return stream.ToArray(); 
    } 
} 

void Main() 
{ 
    Class_B obj = new Class_B() 

    byte[] data = ObjectToByteArray(obj); 
} 
+1

错误是完全描述了这个问题 - 你不能将这个属性应用到除字段以外的任何东西(你试图将它应用到属性)。 – Alex 2011-03-29 15:18:27

回答

9

错误告诉你,你需要知道的一切:非序列化只能适用于域,但您尝试将其应用到的属性,虽然自动属性。

您唯一真正的选择是不使用该栏位的自动属性,如StackOverflow question中所述。

7

尽量明确使用支持字段,你可以马克为[非序列化]

[Serializable] 
public class B_Class 
{ 
    [NonSerialized] 
    private A_Class a; // backing field for your property, which can have the NonSerialized attribute. 
    public int ID { get; set; } 

    public A_Class A // property, which now doesn't need the NonSerialized attribute. 
    { 
    get { return a;} 
    set { a= value; } 
    } 
} 

的问题是,NonSerialized属性是有效的领域,但没有属性,因此,你不能用它与自动实现的属性相结合。