在 C# 中返回指向 class 变量的指针

Returning pointer to a class variable in C#

我目前正在为我的研究编写实验作业,我想创建一个函数 return 指向来自同一个 class 变量的指针。

int* getProc(int id)
    {
        switch (id)
        {
            case 1:
                return &this.proc1tasks;
                break;
            case 2:
                return &this.proc2tasks;
                break;
        }
    }

但是对于每个 &this.proc#tasks VS 2013 表示

Error 2 Pointers and fixed size buffers may only be used in an unsafe context

有什么办法可以让它像我想象的那样工作吗?

让方法 return 有一个委托,在调用时将评估相关变量的值:

public Func<int> getProc(int id)
{
    switch (id)
    {
        case 1:
            return () => proc1tasks;
        case 2:
            return () => proc2tasks;
    }
}

这将为您提供一个对象,该对象在被调用时(很像您要取消引用的指针)将为您提供该字段的当前值。