c# - 了解 C# 中的非托管关键字

情况

我正在阅读有关 C# 7.x 到 8.0 中新增功能的 MSDN 文档,并找到了这些文章(doc1、doc2)

所以我决定创建一个小测试。

代码

Pointer.cs

internal readonly unsafe struct Pointer<T>
    where T : unmanaged
{
    private readonly void* mValue;

    internal Pointer(T value)
    {
        //fixed (T* val = &value) <--- Error: You cannot use the fixed statement to take the adress of an already fixed expression.
        //    mValue = val;

        mValue = &value;
    }

    public static implicit operator Pointer<T>(T value)
    {
        return new Pointer<T>(value);
    }

    public static implicit operator string(Pointer<T> value)
    {
        var ptr = (T*)value.mValue;
        return ptr->ToString(); // returns random values (maybe adresses).
    }
}

Program.cs

class Program
{
    static void Main(string[] args)
    {
        Pointer<int> ptr = 2;

        Console.WriteLine(ptr); // prints random values (maybe adresses).
    }
}

问题

为什么我不允许在构造函数中使用 fixed 语句。我的意思是这是有道理的,它会抛出一个错误。我说过 T 应该是 unmanaged,所以我认为它会在内部自动使用 fixed 关键字。但如果是这样,那为什么我会得到随机值。

最佳答案

根据documentation for unmanaged types T 将是某种不能包含对托管类型的引用的值类型。因此它将分配在堆栈上。当构造函数返回时,堆栈将被弹出,指针将指向某个未定义的值。您不能将 fixed 用于堆栈上分配的内容,因为无论如何都不能被垃圾收集器移动,因此被认为是“固定的”。

https://stackoverflow.com/questions/61360020/

相关文章:

node.js - 如何增加 Node.js 中的最大调用堆栈大小

php - 更改 Woocommerce 管理员订单列表时间和日期格式

java-8 - jdk 11 中缺少外部 jar 文件

javascript - postgres : relation does not exist wh

javascript - 如何在保持背景颜色不变的情况下为 Puppeteer 生成的 pdf 页面

flutter - 如何在 Flutter 中禁用 SnackBar 的淡入/淡出动画?

google-cloud-platform - 自托管 Gitlab,在 Google Cloud

ionic-framework - Ionic 5 键盘的问题

ios - SwiftUI View 未更新以反射(reflect) UIViewControlle

python - 当没有 activate.bat 并且我是凡人时,如何在虚拟环境中的任务调度程序中