难道typeof运算()运算符在C#在堆上分配一个新的类型的对象,或返回一个现有的? [英] Does the typeof() operator in C# allocate a new Type object on the heap, or return an existing one?

查看:105
本文介绍了难道typeof运算()运算符在C#在堆上分配一个新的类型的对象,或返回一个现有的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该是不言自明,但是这是在我想避免,以避免触发GC分配的实时XNA代码的上下文。因此,如果与已经加载的类型相关的管理型对象总是出现在运行时我在想,如果typeof运算()实际上(在运行时可能来自一些非托管元数据)在堆上构造一个新的类型的对象,这将是垃圾收集。随意点出被连问这个问题,以及=)

Should be pretty self-explanatory, but this is in the context of real-time XNA code where I want to avoid allocations in order to avoid triggering GC. So I'm wondering if the managed Type objects associated with the types that have been loaded are always present in the runtime, or if typeof() actually constructs a new Type object (presumably from some unmanaged metadata in the runtime) on the heap, which will be garbage collected. Feel free to point out any ignorant assumptions/misconceptions revealed by even asking this question as well =)

推荐答案

没有,类型缓存透露任何无知假设/误解,它总是返回相同的静态只读实例

No, types are cached, it returns always the same static readonly instance.

您可以写这个样品测试程序来验证这一点:)

You can write this sample test program to verify this :)

static void MyTest()
{
    if (object.ReferenceEquals(typeof(int), typeof(int))
        Console.WriteLine("Yippie! they are the same!");
    else
        Console.WriteLine("WTF?");
}

同样适用于GetType方法和所有其他反射功能,喜欢把自己的属性,方法,字段,属性和一切。

The same apply for GetType method and for every other reflection function, like getting properties, methods, fields, attributes and everything else.

这篇关于难道typeof运算()运算符在C#在堆上分配一个新的类型的对象,或返回一个现有的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆