【问题标题】:Take the address of a ref parameter取一个 ref 参数的地址
【发布时间】:2011-07-29 08:24:46
【问题描述】:

我的代码如下

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 参数的地址是否像上面测试中显示的那样可靠。

【问题讨论】:

  • 顺便说一句,我还想知道结构/类的值类型静态字段是否会在其生命周期内保持其地址不变。

标签: c# unsafe


【解决方案1】:

据我所知,是的,当您在 fixed 块中时,GC 不会重新定位 arg。一旦在fixed 块之外,变量就会被取消固定,因此会被 GC 重定位。

关于 static struct/class/field 将其地址固定在内存中,答案是否定的。它们会像任何其他对象一样被重新定位。不保证本身不会仅仅因为它被标记为static而在内存中没有未来的重定位。

static 的意义与编译器在编译某个类/结构/字段时所拥有的知识和确定性有关。它与内存位置以及它们是否固定等无关。用 Eric Lippert 的话来说:

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

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多