- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
为什么在 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?
看起来有效,因为它只包含一个 bool
和 int
字段。
最佳答案
引用 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/
我是一名优秀的程序员,十分优秀!