您的位置:首页 > 编程语言 > C#

c#中动态对象的RuntimeTypeHandle

2015-08-07 16:12 316 查看
它表示使用内部元数据标记的类型。

MSDN地址:https://msdn.microsoft.com/zh-cn/library/system.runtimetypehandle.aspx

PS:Type 是一个表示类型的抽象类;RuntimeType 是 Type 针对载入类型信息的具体实现;RuntimeTypeHandle 则是类型唯一的抽象句柄。参阅http://www.cnblogs.com/dudu/articles/9984.html【Type,
RuntimeType and RuntimeTypeHandle】,此处摘录部分内容和代码:

RuntimeType 是 System 名字空间的内部类,用于实现对普通类型的运行时信息提供代码。Type中很多抽象函数如 Type.GetMethodImpl 都是在 RuntimeType 中实现的。与 TypeBuilder 等不同,RuntimeType 是类型的运行时表现。
    RuntimeTypeHandle 是运行时类型的抽象句柄,结构内部实际上是一个 Unamanged 指针。可以使用 Type.GetTypeFromHandle() 函数、Type.TypeHandle 属性和 Type.GetTypeHandle() 函数,完成在类型句柄、类型和对象之间的双向转换。例如:
MyClass1 cls = new MyClass1();

Debug.Assert(cls.GetType().TypeHandle.Equals(Type.GetTypeHandle(cls)));
Debug.Assert(Type.GetTypeFromHandle(cls.GetType().TypeHandle) == typeof(MyClass1));


using System;
using System.Reflection;

public class MyClass1
{
    private int x=0;
    public int MyMethod()
    {
        return x;
    }
}

public class MyClass2
{
    public static void Main()
    {
        MyClass1 myClass1 = new MyClass1();

        // Get the RuntimeTypeHandle from an object.
        RuntimeTypeHandle myRTHFromObject = Type.GetTypeHandle(myClass1);
        // Get the RuntimeTypeHandle from a type.
        RuntimeTypeHandle myRTHFromType = typeof(MyClass1).TypeHandle;

        Console.WriteLine("\nmyRTHFromObject.Value:  {0}", myRTHFromObject.Value);
        Console.WriteLine("myRTHFromObject.GetType():  {0}", myRTHFromObject.GetType());
        Console.WriteLine("Get the type back from the handle...");
        Console.WriteLine("Type.GetTypeFromHandle(myRTHFromObject):  {0}", 
            Type.GetTypeFromHandle(myRTHFromObject));

        Console.WriteLine("\nmyRTHFromObject.Equals(myRTHFromType):  {0}", 
            myRTHFromObject.Equals(myRTHFromType));

        Console.WriteLine("\nmyRTHFromType.Value:  {0}", myRTHFromType.Value);
        Console.WriteLine("myRTHFromType.GetType():  {0}", myRTHFromType.GetType());
        Console.WriteLine("Get the type back from the handle...");
        Console.WriteLine("Type.GetTypeFromHandle(myRTHFromType):  {0}", 
            Type.GetTypeFromHandle(myRTHFromType));
    }
}

/* This code example produces output similar to the following:

myRTHFromObject.Value:  799464
myRTHFromObject.GetType():  System.RuntimeTypeHandle
Get the type back from the handle...
Type.GetTypeFromHandle(myRTHFromObject):  MyClass1

myRTHFromObject.Equals(myRTHFromType):  True

myRTHFromType.Value:  799464
myRTHFromType.GetType():  System.RuntimeTypeHandle
Get the type back from the handle...
Type.GetTypeFromHandle(myRTHFromType):  MyClass1
 */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: