NonSerializedAttribute NonSerializedAttribute NonSerializedAttribute NonSerializedAttribute Class

Definição

Indica que um campo de uma classe serializável não deve ser serializado.Indicates that a field of a serializable class should not be serialized. Essa classe não pode ser herdada.This class cannot be inherited.

public ref class NonSerializedAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Field, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.AttributeUsage(System.AttributeTargets.Field, Inherited=true)]
public sealed class NonSerializedAttribute : Attribute
type NonSerializedAttribute = class
    inherit Attribute
Public NotInheritable Class NonSerializedAttribute
Inherits Attribute
Herança
NonSerializedAttributeNonSerializedAttributeNonSerializedAttributeNonSerializedAttribute
Atributos

Exemplos

O exemplo a seguir demonstra a serialização de um objeto marcado SerializableAttribute com o atributo e o comportamento de um campo marcado com NonSerializedAttribute o no objeto serializado.The following example demonstrates serialization of an object marked with the SerializableAttribute attribute, and the behavior of a field marked with the NonSerializedAttribute in the serialized object.

Observação

O código usa a SoapFormatter classe para serializar o objeto.The code uses the SoapFormatter class to serialize the object. A classe é encontrada em System. Runtime. Serialization. Formatters. SOAP. dll, que não é carregado por padrão em um projeto.The class is found in the system.runtime.serialization.formatters.soap.dll, which is not loaded by default into a project. Para executar o código, você deve adicionar uma referência à DLL para o seu projeto.To run the code, you must add a reference to the DLL to your project.

#using <system.dll>
#using <system.messaging.dll>
#using <System.Runtime.Serialization.Formatters.Soap.dll>

using namespace System;
using namespace System::IO;
using namespace System::Runtime::Serialization::Formatters::Soap;

// A test object that needs to be serialized.

[Serializable]
ref class TestSimpleObject
{
private:
   int member1;
   String^ member2;
   String^ member3;
   double member4;

public:

   // A field that is not serialized.

   [NonSerialized]
   String^ member5;
   TestSimpleObject()
   {
      member1 = 11;
      member2 = "hello";
      member3 = "hello";
      member4 = 3.14159265;
      member5 = "hello world!";
   }

   void Print()
   {
      Console::WriteLine( "member1 = ' {0}'", member1 );
      Console::WriteLine( "member2 = ' {0}'", member2 );
      Console::WriteLine( "member3 = ' {0}'", member3 );
      Console::WriteLine( "member4 = ' {0}'", member4 );
      Console::WriteLine( "member5 = ' {0}'", member5 );
   }

};

int main()
{
   // Creates a new TestSimpleObject object.
   TestSimpleObject^ obj = gcnew TestSimpleObject;
   Console::WriteLine( "Before serialization the Object* contains: " );
   obj->Print();

   // Opens a file and serializes the object into it in binary format.
   Stream^ stream = File::Open( "data.xml", FileMode::Create );
   SoapFormatter^ formatter = gcnew SoapFormatter;

   //BinaryFormatter* formatter = new BinaryFormatter();
   formatter->Serialize( stream, obj );
   stream->Close();

   // Empties obj.
   obj = nullptr;

   // Opens file S"data.xml" and deserializes the object from it.
   stream = File::Open( "data.xml", FileMode::Open );
   formatter = gcnew SoapFormatter;

   //formatter = new BinaryFormatter();
   obj = dynamic_cast<TestSimpleObject^>(formatter->Deserialize( stream ));
   stream->Close();
   Console::WriteLine( "" );
   Console::WriteLine( "After deserialization the object contains: " );
   obj->Print();
}

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
//using System.Runtime.Serialization.Formatters.Binary;

public class Test {
   public static void Main()  {

      // Creates a new TestSimpleObject object.
      TestSimpleObject obj = new TestSimpleObject();

      Console.WriteLine("Before serialization the object contains: ");
      obj.Print();

      // Opens a file and serializes the object into it in binary format.
      Stream stream = File.Open("data.xml", FileMode.Create);
      SoapFormatter formatter = new SoapFormatter();

      //BinaryFormatter formatter = new BinaryFormatter();

      formatter.Serialize(stream, obj);
      stream.Close();

      // Empties obj.
      obj = null;

      // Opens file "data.xml" and deserializes the object from it.
      stream = File.Open("data.xml", FileMode.Open);
      formatter = new SoapFormatter();

      //formatter = new BinaryFormatter();

      obj = (TestSimpleObject)formatter.Deserialize(stream);
      stream.Close();

      Console.WriteLine("");
      Console.WriteLine("After deserialization the object contains: ");
      obj.Print();
   }
}


// A test object that needs to be serialized.
[Serializable()]
public class TestSimpleObject  {

    public int member1;
    public string member2;
    public string member3;
    public double member4;

    // A field that is not serialized.
    [NonSerialized()] public string member5;

    public TestSimpleObject() {

        member1 = 11;
        member2 = "hello";
        member3 = "hello";
        member4 = 3.14159265;
        member5 = "hello world!";
    }


    public void Print() {

        Console.WriteLine("member1 = '{0}'", member1);
        Console.WriteLine("member2 = '{0}'", member2);
        Console.WriteLine("member3 = '{0}'", member3);
        Console.WriteLine("member4 = '{0}'", member4);
        Console.WriteLine("member5 = '{0}'", member5);
    }
}
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Soap




Public Class Test
   
   Public Shared Sub Main()
      
      ' Creates a new TestSimpleObject object.
      Dim obj As New TestSimpleObject()
      
      Console.WriteLine("Before serialization the object contains: ")
      obj.Print()
      
      ' Opens a file and serializes the object into it in binary format.
      Dim stream As Stream = File.Open("data.xml", FileMode.Create)
      Dim formatter As New SoapFormatter()
      


      formatter.Serialize(stream, obj)
      stream.Close()
      
      ' Empties obj.
      obj = Nothing
      
      ' Opens file "data.xml" and deserializes the object from it.
      stream = File.Open("data.xml", FileMode.Open)
      formatter = New SoapFormatter()



      obj = CType(formatter.Deserialize(stream), TestSimpleObject)
      stream.Close()
      
      Console.WriteLine("")
      Console.WriteLine("After deserialization the object contains: ")
      obj.Print()

   End Sub 'Main

End Class 'Test


' A test object that needs to be serialized.
<Serializable()> Public Class TestSimpleObject
   
   Public member1 As Integer
   Public member2 As String
   Public member3 As String
   Public member4 As Double
   
   ' A member that is not serialized.
   <NonSerialized()> Public member5 As String  
  
   
   Public Sub New()     
      member1 = 11
      member2 = "hello"
      member3 = "hello"
      member4 = 3.14159265
      member5 = "hello world!"
   End Sub 'New
      
   
   Public Sub Print()      
      Console.WriteLine("member1 = '{0}'", member1)
      Console.WriteLine("member2 = '{0}'", member2)
      Console.WriteLine("member3 = '{0}'", member3)
      Console.WriteLine("member4 = '{0}'", member4)
      Console.WriteLine("member5 = '{0}'", member5)
   End Sub 'Print

End Class 'TestSimpleObject

Comentários

Ao usar as BinaryFormatter classes SoapFormatter ou para serializar um objeto, use NonSerializedAttribute o atributo para impedir que um campo seja serializado.When using the BinaryFormatter or SoapFormatter classes to serialize an object, use the NonSerializedAttribute attribute to prevent a field from being serialized. Por exemplo, você pode usar esse atributo para impedir a serialização de dados confidenciais.For example, you can use this attribute to prevent the serialization of sensitive data.

Os objetos de destino para NonSerializedAttribute o atributo são campos públicos e privados de uma classe serializável.The target objects for the NonSerializedAttribute attribute are public and private fields of a serializable class. Por padrão, as classes não são serializáveis, a menos SerializableAttributeque sejam marcadas com.By default, classes are not serializable unless they are marked with SerializableAttribute. Durante o processo de serialização, todos os campos públicos e privados de uma classe são serializados por padrão.During the serialization process all the public and private fields of a class are serialized by default. Os campos marcados NonSerializedAttribute com são excluídos durante a serialização.Fields marked with NonSerializedAttribute are excluded during serialization. Se você estiver usando a XmlSerializer classe para serializar um objeto, use XmlIgnoreAttribute a classe para obter a mesma funcionalidade.If you are using the XmlSerializer class to serialize an object, use the XmlIgnoreAttribute class to get the same functionality. Como alternativa, implemente ISerializable a interface para controlar explicitamente o processo de serialização.Alternatively, implement the ISerializable interface to explicitly control the serialization process. Observe que as classes implementadas ISerializable ainda devem ser marcadas com. SerializableAttributeNote that classes that implement ISerializable must still be marked with SerializableAttribute.

Para aplicar a NonSerializedAttribute classe a um evento, defina o local do atributo como campo, conforme mostrado no código C# a seguir.To apply the NonSerializedAttribute class to an event, set the attribute location to field, as shown in the following C# code.

[field:NonSerializedAttribute()]   
public event ChangedEventHandler Changed;  

Se um campo não for serializado, mas ainda exigir um valor padrão que deve ser fornecido após a desserialização, você poderá criar um método que forneça o campo com um valor e, em seguida OnDeserializedAttribute , aplicar o ao método.If a field is not serialized, but it still requires a default value that must be supplied after deserialization, you can create a method that supplies the field with a value, then apply the OnDeserializedAttribute to the method.

Para obter mais informações sobre como usar atributos, consulte atributos.For more information about using attributes, see Attributes.

Construtores

NonSerializedAttribute() NonSerializedAttribute() NonSerializedAttribute() NonSerializedAttribute()

Inicializa uma nova instância da classe NonSerializedAttribute.Initializes a new instance of the NonSerializedAttribute class.

Métodos

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Retorna um valor que indica se essa instância é igual a um objeto especificado.Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Retorna o código hash para essa instância.Returns the hash code for this instance.

(Inherited from Attribute)
GetType() GetType() GetType() GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
Match(Object) Match(Object) Match(Object) Match(Object)

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Inherited from Object)

Implantações explícitas de interface

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

Propriedades

TypeId TypeId TypeId TypeId

Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

Aplica-se a

Veja também