gpt4 book ai didi

c# - c#中的托管指针数组

转载 作者:行者123 更新时间:2023-11-30 17:25:40 27 4
gpt4 key购买 nike

我在创建托管指针数组时遇到了问题。

我试过了

public unsafe class Car
{
public int speed;

public Car()
{
speed = 0;
}

public Car(int speed)
{
this.speed = speed;
}
}

class Program
{
public static unsafe void Main(string[] args)
{
var arr = new Car[10]; // 1st way
fixed(Car* ptr = arr)
{}

Car* arr = stackalloc Car[10]; // 2nd way
}
}

两次尝试后,我得到相同的错误:“无法获取地址或大小或定义托管类型的指针”。有人知道如何解决吗?

最佳答案

嗯,作为C# specs说:

Unlike references (values of reference types), pointers are nottracked by the garbage collector—the garbage collector has noknowledge of pointers and the data to which they point.

For thisreason a pointer is not permitted to point to a reference or to astruct that contains references, and the referent type of a pointermust be an unmanaged-type. An unmanaged-type is any type that isn’t areference-type and doesn’t contain reference-type fields at any levelof nesting. In other words, an unmanaged-type is one of the following:

sbyte, byte, short, ushort, int, uint, long, ulong, char, float,double, decimal, or bool.

Any enum-type.

Any pointer-type. Any user-defined struct-type that contains fields of unmanaged-types only.

关于c# - c#中的托管指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57946096/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com