在.NET固定块 [英] fixed block in .net

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

问题描述

我是当定块被要求就有点糊涂了。我有例子,给了我以下矛盾的情形:

I am a bit confused on when fixed block is required. I have example which gives me a contradicting scenario below:

enum RoomType { Economy, Buisness, Executive, Deluxe };

struct HotelRoom
{
    public int Number;
    public bool Taken;
    public RoomType Category;

    public void Print()
    {
        String status = Taken ? "Occupied" : "available";
        Console.WriteLine("Room {0} is of {1} class and is currently {2}", Number, Category, status);
    }
}

我做了一个函数,它需要一个指向一个的空房

private unsafe static void Reserve(HotelRoom* room)
{
    if (room->Taken)
        Console.WriteLine("Cannot reserve room {0}", room->Number);
    else
        room->Taken = true;
}

在main方法我有以下几点:

In the main method I have the following:

unsafe static void Main(string[] args)
{
    HotelRoom[] myfloor = new HotelRoom[4];
    for (int i = 0; i < myfloor.Length; i++)
    {
        myfloor[i].Number = 501 + i;
        myfloor[i].Taken = false;
        myfloor[i].Category = (RoomType)i;
    }
    HotelRoom Room =  myfloor[1];
    Reserve(&Room);   //I am able to do this without fixed block.
    //Reserve(&myfloor[1]);  //Not able to do this so have to use fixed block below. 

    fixed (HotelRoom* pRoom = &myfloor[1])
    {
        Reserve(pRoom);
    }

    myfloor[1].Print();
    Room.Print();
}

我的困惑是,我能够做到储备(安培;房间)而不是储备(安培; myfloor [1])。我认为他们正在做同样的事情 - 通过一个的空房的memeory地址结构的预订功能。为什么需要固定做到这一点?

My confusion is I am able to do Reserve(&Room) but not Reserve(&myfloor[1]). I think they're doing the same thing - passing memeory address of a HotelRoom struct to the Reserve function. Why do I need fixed to do this?

推荐答案

客房是存储在堆栈中,一个局部变量,而 myfloor 存储在堆中。垃圾收集器堆将对象移动到压缩它(不会忽略会改变),所以你需要针他们。这就是为什么你需要固定语句。

Room is a local variable which is stored on stack, while myfloor is stored in heap. Garbage collector can move objects in the heap to compact it (adresses will change), so you need to "pin" them. That's why you need fixed statement.

更新:

此外,有一种方法来分配内存堆栈insted的堆:

Also, there is a way to allocate memory on stack insted of heap:

的空房* FIB = stackalloc的空房[4];

在这种情况下,你不需要固定语句。

In this case you won't need fixed statement.

小disclamer:能做到这一点并不意味着你当然应该。正如其他人已经提到,这是写作code非常non-.NET的方式,所以我认为这个问题是理论上的。

Small disclamer: being able to do this doesn't mean you should of course. As others already mentioned, it is very non-.NET way of writing code, so I just consider this question is theoretical.

这篇关于在.NET固定块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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