投射优化和GCHandle

时间:2015-12-14 19:10:37

标签: c# casting

我有一个对象只能通过隐式转换运算符来访问内部字节[]。像这样:

class Thing
{
    private byte[] array;
    public static implicit operator byte[](Thing thing) => thing.array;
}

我需要将该数组固定为IntPtr:

void Foo(Thing thing)
{
    byte[] array = thing;  // cast to access inner byte[]
    var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
    DoSomethingWithArray(GCHandle.ToIntPtr(handle));
    handle.Free();
}

似乎有可能(在某些情况下我没有遇到过)编译器优化掉将导致错误对象被固定的转换。是吗?

1 个答案:

答案 0 :(得分:2)

你正在传递一个引用,所以不应该错误的东西固定。行INSERT将像执行byte[] array = thing;一样执行。看起来你正在返回对最里面数组的引用。这将是固定的。

编辑:为什么它不会被优化掉的原因是因为它不再是演员了;当你编写自己的运算符时,它是一个函数调用。函数本身可能是内联的,但行为不会简单地消失。