📜  C#| Type.GetTypeFromHandle()方法

📅  最后修改于: 2021-05-30 00:02:24             🧑  作者: Mango

Type.GetTypeFromHandle()方法用于获取指定类型句柄引用的类型。

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

范例1:

// C# program to demonstrate the
// Type.GetTypeFromHandle() Method
using System;
using System.Globalization;
using System.Reflection;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // creating and initializing object Type
        Type type = typeof(int);
  
        // creating object of RuntimeTypeHandle 
        // and getting instance of type
        RuntimeTypeHandle handle = Type.GetTypeHandle(type);
  
        // Getting the type referenced by
        // the specified RuntimeTypeHandle,
        // using GetTypeFromHandle() Method
        Type outtype = Type.GetTypeFromHandle(handle);
  
        // Display the Result
        Console.WriteLine("Type referenced is {0}", outtype);
        Console.WriteLine("Attributes are: " + outtype.Attributes);
    }
}
输出:
Type referenced is System.RuntimeType
Attributes are: AutoLayout, AnsiClass, Class, SequentialLayout, Serializable, BeforeFieldInit

范例2:

// C# program to demonstrate the
// Type.GetTypeFromHandle() Method
using System;
using System.Globalization;
using System.Reflection;
  
// Defining Empty struct
struct Empty {}
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // creating and initializing object Type
        Type type = typeof(Empty);
  
        // creating object of RuntimeTypeHandle 
        // and getting instance of type
        RuntimeTypeHandle handle = Type.GetTypeHandle(type);
  
        // Getting the type referenced by
        // the specified RuntimeTypeHandle,
        // using GetTypeFromHandle() Method
        Type outtype = Type.GetTypeFromHandle(handle);
  
        // Display the Result
        Console.WriteLine("Type referenced is {0}", outtype);
        Console.WriteLine("Attributes are: " + outtype.Attributes);
    }
}
输出:
Type referenced is System.RuntimeType
Attributes are: AutoLayout, AnsiClass, Class, SequentialLayout, Serializable, BeforeFieldInit

参考:

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