微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 获取ref参数的地址

我的代码如下

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);
    }
}

我想知道参考ref参数的地址是否与上面测试中显示的一样可靠.

解决方法

据我所知,是的,当你在固定区块时,GC不会重新定位arg.一旦在固定块之外,变量就被取消固定,因此需要由GC重新定位.

关于一个静态结构/类/字段保持其地址固定在内存中,答案是否定的.它们像任何其他对象一样被重新定位.由于它被标记为静态,因此没有保证在内存中不会有未来的重定位.

静态的意义与编译器在某个类/结构/字段的编译时具有的知识和确定性有关.它与内存位置无关,它们是否固定等等.用Eric Lippert的话来说:

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐