📜  C#| Type.GetTypeHandle()方法

📅  最后修改于: 2021-05-29 15:11:21             🧑  作者: Mango

Type.GetTypeHandle()方法用于获取指定对象的Type的句柄。

下面的程序说明了Type.GetTypeHandle()方法的用法:

范例1:

// C# program to demonstrate the
// Type.GetTypeHandle() Method
using System;
using System.Globalization;
using System.Reflection;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // try-catch block for handling Exception
        try {
  
            // creating and initializing object Type
            Type type = typeof(int);
  
            // getting handle of given type
            // by using GetTypeHandle() Method
            RuntimeTypeHandle handle = Type.GetTypeHandle(type);
  
            // Display the Result
            Console.WriteLine("Type referenced is {0}", handle);
        }
  
        // catch ArgumentNullException here
        catch (ArgumentNullException e) 
        {
            Console.WriteLine("object is null.");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}

输出:

Type referenced is System.RuntimeTypeHandle

范例2:

// C# program to demonstrate the
// Type.GetTypeHandle() Method
using System;
using System.Globalization;
using System.Reflection;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // try-catch block for handling Exception
        try {
  
            // creating and initializing object Type
            Type type = typeof(int);
  
            // getting handle of given type
            // by using GetTypeHandle() Method
            RuntimeTypeHandle handle = Type.GetTypeHandle(null);
  
            // Display the Result
            Console.WriteLine("Type referenced is {0}", handle);
        }
  
        // catch ArgumentNullException here
        catch (ArgumentNullException e)
        {
            Console.WriteLine("object is null.");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}

输出:

object is null.
Exception Thrown: System.ArgumentNullException

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.type.gettypehandle?view=netframework-4.8