SerializationInfo.GetValue(String, Type) 方法

定义

SerializationInfo 存储中检索一个值。

C#
public object? GetValue (string name, Type type);
C#
public object GetValue (string name, Type type);

参数

name
String

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

type
Type

要检索的值的 Type。 如果存储的值不能转换为此类型,则系统会引发 InvalidCastException

返回

Object

name 关联的已指定 Type 的对象。

例外

nametypenull

name 关联的值不能转换为 type

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

示例

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

C#
// 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());
   }
}

注解

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

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

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1