取参考参数的地址 [英] Take the address of a ref parameter

查看:131
本文介绍了取参考参数的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

class MyClass
{
    static int iField = 42;
    static void Test(ref int arg)
    {
         unsafe
         {
            fixed(void* pField = &iField)
            fixed(void* pArg = &arg)
            {
                Console.WriteLine ("{0},{1}",(int)pArg,(int)pField);
                //output: 165451772,165451772
            }
         }
    }

    static void Main()
    {
        Test(ref iField);
    }
}



我想知道,如果采取参考地址参数是可靠的,因为它在测试上面显示。

I'd like to know if taking address of ref parameters is as reliable as it showed above in the test.

推荐答案

据我所知,是的,而你是在固定块时,的 GC 的不会搬迁 ARG 。一旦外固定块中的变量是未固定,因此受的 GC

As far as I know, yes while you are in the fixed block, the GC will not relocate arg. Once outside the fixed block the variable is unpinned and thus subject to relocation by the GC.

关于在静态结构/类/字段的保持它的地址固定在内存中,答案是否定的。他们是受搬迁任何其他对象。没有garantee的本身的会有内存中没有未来的搬迁只是因为它被标记为静态

About a static struct/class/field keeping it's address fixed in memory, the answer is no. They are subject to relocation as any other object. There is not garantee per se that there will be no future relocation in memory just because it is marked as static.

静态的意义与知识做和确定性,编译器在一定的类/结构/场的编译时间的你有什么。它无关的存储位置,并将其固定与否等。埃里克利珀的话:

The significance of static has to do with the knowledge and certainties the compiler has at compile time of a certain class/struct/field what have you. It has nothing to do with memory locations and them being fixed or not, etc. In Eric Lippert's words:

静态方法被称为静因为它总是可以准确地确定,在编译的时候,有什么方法将被调用。也就是说,该方法可以仅仅通过代码的静态分析来解决。

Static methods are called "static" because it can always be determined exactly, at compile time, what method will be called. That is, the method can be resolved solely by static analysis of the code.

这篇关于取参考参数的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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