SerializationInfo.GetValue(String, Type) 方法

定义

从存储区 SerializationInfo 中检索值。

public:
 System::Object ^ GetValue(System::String ^ name, Type ^ type);
public object GetValue(string name, Type type);
member this.GetValue : string * Type -> obj
Public Function GetValue (name As String, type As Type) As Object

参数

name
String

与要检索的值关联的名称。

type
Type

Type要检索的值。 如果存储的值无法转换为此类型,系统将引发一个 InvalidCastException

返回

与 . 关联的name指定Type对象。

例外

nametypenull.

与关联的 name 值无法转换为 type

当前实例中找不到具有指定名称的元素。

示例

下面的代码示例演示如何使用 GetValue 该方法:

// A serializable LinkedList example.  For the full LinkedList implementation
// see the Serialization sample.
[Serializable()]
class LinkedList: ISerializable {

   public static void Main() {}

   Node m_head = null;
   Node m_tail = null;

   // Serializes the object.
   public void GetObjectData(SerializationInfo info, StreamingContext context){
      // Stores the m_head and m_tail references in the SerializationInfo info.
      info.AddValue("head", m_head, m_head.GetType());
      info.AddValue("tail", m_tail, m_tail.GetType());
   }

   // Constructor that is called automatically during deserialization.
   // Reconstructs the object from the information in SerializationInfo info
   private LinkedList(SerializationInfo info, StreamingContext context)
   {
      Node temp = new Node(0);
      // Retrieves the values of Type temp.GetType() from SerializationInfo info
      m_head = (Node)info.GetValue("head", temp.GetType());
      m_tail = (Node)info.GetValue("tail", temp.GetType());
   }
}
' A serializable LinkedList example.  For the full LinkedList implementation
' see the Serialization sample.
<Serializable()> Class LinkedList
    Implements ISerializable

    Public Shared Sub Main()
    End Sub

    Private m_head As Node = Nothing
    Private m_tail As Node = Nothing    
    
    ' Serializes the object.
    Public Sub GetObjectData(info As SerializationInfo, _
    context As StreamingContext) Implements ISerializable.GetObjectData
    
        ' Stores the m_head and m_tail references in the SerializationInfo info.
        info.AddValue("head", m_head, m_head.GetType())
        info.AddValue("tail", m_tail, m_tail.GetType())
    End Sub
    
    
    ' Constructor that is called automatically during deserialization.
    ' Reconstructs the object from the information in SerializationInfo info.
    Private Sub New(info As SerializationInfo, context As StreamingContext)
        Dim temp As New Node(0)
        ' Retrieves the values of Type temp.GetType() from SerializationInfo info.
        m_head = CType(info.GetValue("head", temp.GetType()), Node)
        m_tail = CType(info.GetValue("tail", temp.GetType()), Node)
    End Sub
End Class

注解

如果存储在其中 SerializationInfo 的数据的类型为所请求的类型(或其派生类之一),则直接返回该值。 否则, IFormatterConverter.Convert 将调用它以将其转换为适当的类型。

方法返回 GetValue 的值始终可以安全地强制转换为参数中指定的 type 类型。

适用于