什么是退出序列化器

下面的代码表示使用 SerializableNonSerialized 属性的 Opt-Out 方法的示例。

/// <summary>
/// Represents a student.
/// </summary>
[Serializable]
public class Student
{
    /// <summary>
    /// Gets or sets student number.
    /// </summary>
    public string StudentNumber { get; set; }

    /// <summary>
    /// Gets or sets first name.
    /// </summary>
    public string FirstName { get; set; }

    /// <summary>
    /// Gets or sets last name.
    /// </summary>
    public string LastName { get; set; }

    /// <summary>
    /// Gets or sets marks obtained.
    /// </summary>
    [NonSerialized]
    public string MarksObtained { get; set; }
}

/// <summary>
/// A service that provides the operations for student.
/// </summary>
[ServiceContract]
public interface IStudentService
{
    //Service contract code here. Example given.
    
    /// <summary>
    /// Adds a student into the system.
    /// </summary>
    /// <param name="student">Student to be added.</param>
    [OperationContract]
    void AddStudent(Student student);
}

在上面的例子中,我们明确地将 MarksObtained 属性标记为 [NonSerialized] 属性,因此除了其他属性之外它将被忽略。希望这可以帮助!