c# - 泛型指针

标签 c# pointers generics

为什么在 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 not tracked by the garbage collector—the garbage collector has no knowledge of pointers and the data to which they point. For this reason a pointer is not permitted to point to a reference or to a struct that contains references, and the referent type of a pointer must be an unmanaged-type.

An unmanaged-type is any type that isn’t a reference-type or constructed type, and doesn’t contain reference-type or constructed type fields at any level of 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 is not 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/

相关文章:

c# - 将分割字符串交错作为列表 C#

c# - Visual Studio 2019 未显示 .NET 5 框架

c - 在另一个函数中修改 C 中的字符串数组

c - 双星号和 C 中的 `malloc`

java - 在通用列表中插入删除的元素

java - 是否有机会在我的项目中使用 Class <?, ?> ?

c# - ASP.NET 4.5.2 MVC 项目模板中的身份验证系统是否适合在实际应用程序中使用?

c++ - C++中的内存分配顺序

java - Spring JpaRepository 使用通用实体

c# - 当属性名称与类名称相同时,IntelliSense 不使用扩展方法