gpt4 book ai didi

c# - 泛型指针

转载 作者:太空狗 更新时间:2023-10-29 22:36:50 28 4
gpt4 key购买 nike

为什么在 C# 中使用指向泛型类型的指针是无效的? int?* 无效,而 typeof(int?).MakePointerType() 不会产生异常。

根据 MSDN , 一个指针可以是:

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.

我没有看到与泛型相关的任何限制。 int? 看起来有效,因为它只包含一个 boolint 字段。

最佳答案

引用 C# 5.0 规范§18.2 指针类型

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 or constructed type, and doesn’t contain reference-typeor constructed type fields at any level of nesting. In other words, anunmanaged-type is one of the following:

  • sbyte, byte, short, ushort,int, uint, long, ulong, char, float, double, decimal, or bool.
  • Anyenum-type.
  • Any pointer-type.
  • Any user-defined struct-type that isnot a constructed type and contains fields of unmanaged-types only.

阻止您的关键部分是 constructed type限制。

来自 §1.6.3 类型参数(强调我的)

A generic type with type arguments provided, like Pair<int,string> above, is called a constructed type.

您指定类型参数的任何泛型都被视为构造类型,构造类型不允许在指针中。这就是为什么 Nullable<int>不允许。

关于c# - 泛型指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30676126/

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