我有以下简单的测试:
class C<T>
{
public struct A
{
int x;
}
}
class Program
{
static unsafe void Main(string[] args)
{
IntPtr p = new IntPtr();
var a = (C<int>.A*)p.ToPointer();
}
}
Run Code Online (Sandbox Code Playgroud)
代码生成错误CS0208:
Cannot take the address of, get the size of, or declare a pointer to a managed
type ('C<int>.A')
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释为什么在这种情况下结构被视为"托管"?
Mik*_*ray 20
C#5规范的第18.2节:
非托管类型是任何不是引用类型或构造类型的类型,并且在任何嵌套级别都不包含引用类型或构造类型字段.
现在您可能想知道是否C<int>.A有资格作为构造类型(它显然不是引用类型).答案是肯定的.第4.4节定义了构造类型.它特别指出嵌套类型被认为是构造的.它使用Outer<T>.Inner以下作为示例:
class Outer<T>
{
public class Inner {...}
public Inner i; // Type of i is Outer<T>.Inner
}
Run Code Online (Sandbox Code Playgroud)
因为T,这也是其中的C一部分A.这A也意味着通用.并且所有通用类型都被视为托管.
我想,有可能检查是否A使用T并决定.但与所有语言功能一样,它是功能,其实现不会有太多的返回值.
| 归档时间: |
|
| 查看次数: |
1468 次 |
| 最近记录: |