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исключение.
Возвращаемое значение
Объект указанного связанного Type с name.
Исключения
name или type есть null.
Значение, связанное с 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 .