SurrogateSelector Класс

Определение

Внимание!

Formatter-based serialization is obsolete and should not be used.

Содействует форматерам при выборе знака-заместителя сериализации для делегирования в обработку сериализации или десериализации.

public ref class SurrogateSelector : System::Runtime::Serialization::ISurrogateSelector
public class SurrogateSelector : System.Runtime.Serialization.ISurrogateSelector
[System.Obsolete("Formatter-based serialization is obsolete and should not be used.", DiagnosticId="SYSLIB0050", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public class SurrogateSelector : System.Runtime.Serialization.ISurrogateSelector
[System.Runtime.InteropServices.ComVisible(true)]
public class SurrogateSelector : System.Runtime.Serialization.ISurrogateSelector
type SurrogateSelector = class
    interface ISurrogateSelector
[<System.Obsolete("Formatter-based serialization is obsolete and should not be used.", DiagnosticId="SYSLIB0050", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
type SurrogateSelector = class
    interface ISurrogateSelector
[<System.Runtime.InteropServices.ComVisible(true)>]
type SurrogateSelector = class
    interface ISurrogateSelector
Public Class SurrogateSelector
Implements ISurrogateSelector
Наследование
SurrogateSelector
Производный
Атрибуты
Реализации

Примеры

В следующем примере кода показано, как создать суррогатный класс сериализации, который знает, как правильно сериализовать или десериализовать класс, который сам по себе не является сериализуемым. Кроме того, в этом примере также показано, как выполнить восстановление из SerializationException.

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

// This class is not serializable.
class Employee
    {
    public String name, address;

    public Employee(String name, String address)
    {
        this.name = name;
        this.address = address;
    }
}

// This class can manually serialize an Employee object.
sealed class EmployeeSerializationSurrogate : ISerializationSurrogate
{

    // Serialize the Employee object to save the object's name and address fields.
    public void GetObjectData(Object obj,
        SerializationInfo info, StreamingContext context)
    {

        var emp = (Employee) obj;
        info.AddValue("name", emp.name);
        info.AddValue("address", emp.address);
    }

    // Deserialize the Employee object to set the object's name and address fields.
    public Object SetObjectData(Object obj,
        SerializationInfo info, StreamingContext context,
        ISurrogateSelector selector)
    {

        var emp = (Employee) obj;
        emp.name = info.GetString("name");
        emp.address = info.GetString("address");
        return emp;
    }
}

public sealed class App
{
    static void Main()
    {
        // This sample uses the BinaryFormatter.
        IFormatter formatter = new BinaryFormatter();

        // Create a MemoryStream that the object will be serialized into and deserialized from.
        using (Stream stream = new MemoryStream())
        {
            // Create a SurrogateSelector.
            var ss = new SurrogateSelector();

            // Tell the SurrogateSelector that Employee objects are serialized and deserialized
            // using the EmployeeSerializationSurrogate object.
            ss.AddSurrogate(typeof(Employee),
            new StreamingContext(StreamingContextStates.All),
            new EmployeeSerializationSurrogate());

            // Associate the SurrogateSelector with the BinaryFormatter.
            formatter.SurrogateSelector = ss;

            try
            {
                // Serialize an Employee object into the memory stream.
                formatter.Serialize(stream, new Employee("Jeff", "1 Microsoft Way"));
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Serialization failed: {0}", e.Message);
                throw;
            }

            // Rewind the MemoryStream.
            stream.Position = 0;

            try
            {
                // Deserialize the Employee object from the memory stream.
                var emp = (Employee) formatter.Deserialize(stream);

                // Verify that it all worked.
                Console.WriteLine("Name = {0}, Address = {1}", emp.name, emp.address);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Deserialization failed: {0}", e.Message);
                throw;
            }
        }
    }
}

// This code produces the following output.
//
// Name = Jeff, Address = 1 Microsoft Way

Комментарии

Суррогат сериализации предоставляет пользователям объект , который может обрабатывать требования к сериализации другого объекта и при необходимости преобразовывать сериализованные данные.

Конструкторы

SurrogateSelector()
Является устаревшей.

Инициализирует новый экземпляр класса SurrogateSelector.

Методы

AddSurrogate(Type, StreamingContext, ISerializationSurrogate)
Является устаревшей.

Добавляет суррогат в список проверенных суррогатов.

ChainSelector(ISurrogateSelector)
Является устаревшей.

Добавляет заданный ISurrogateSelector, который может обрабатывать конкретный тип объекта для списка суррогатов.

Equals(Object)
Является устаревшей.

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()
Является устаревшей.

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetNextSelector()
Является устаревшей.

Возвращает следующий селектор в цепочку селекторов.

GetSurrogate(Type, StreamingContext, ISurrogateSelector)
Является устаревшей.

Возвращает суррогат для определенного типа.

GetType()
Является устаревшей.

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()
Является устаревшей.

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
RemoveSurrogate(Type, StreamingContext)
Является устаревшей.

Удаляет суррогат, связанный с заданным типом.

ToString()
Является устаревшей.

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к