简体   繁体   English

NonSerialized属性创建错误

[英]NonSerialized attribute creating error

I am trying to serialize an object that has a nested class. 我试图序列化具有嵌套类的对象。 I have tagged the nested class with the [NonSerialized] attribute but I receive an error: 我用[NonSerialized]属性标记了嵌套类,但是收到错误:

Attribute 'NonSerialized' is not valid on this declaration type. 属性“NonSerialized”在此声明类型上无效。 It is only valid on 'field' declarations. 它仅对“字段”声明有效。

How do I omit the nested class from serialization? 如何从序列化中省略嵌套类?

I have included some code that may show what I am trying to do. 我已经包含了一些可能显示我想要做的代码。 Thanks for any help. 谢谢你的帮助。

[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);
}

The error tells you everything you need to know: NonSerialized can only be applied to fields, but you are trying to apply it to a property, albeit an auto-property. 该错误告诉您需要知道的所有内容:NonSerialized只能应用于字段,但您尝试将其应用于属性,尽管是自动属性。

The only real option you have is to not use an auto property for that field as noted in this StackOverflow question . 您唯一真正的选择是不对该字段使用auto属性,如StackOverflow问题中所述

Also consider XmlIgnore attribute on the property: 还要考虑属性上的XmlIgnore属性:

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore.aspx http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore.aspx

IIRC, properties are ignored automatically for binary serialization. IIRC,二进制序列化会自动忽略属性。

Try explicitly using a backing field which you can mark as [NonSerialized] 尝试明确使用可以标记为[NonSerialized]的支持字段

[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; }
  }
}

The problem is that the NonSerialized attribute is valid on fields but not properties, therefore you can't use it in combination with auto-implemented properties. 问题是NonSerialized属性对字段有效,但对属性无效,因此您不能将其与自动实现的属性结合使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM