代码之家  ›  专栏  ›  技术社区  ›  Gabriel

编组。NET泛型类型

  •  13
  • Gabriel  · 技术社区  · 16 年前

    下面是一个C#程序,它尝试 Marshal.SizeOf 关于几种不同的类型:

    using System;
    using System.Runtime.InteropServices;
    
    [StructLayout(LayoutKind.Sequential)]
    class AClass { }
    
    [StructLayout(LayoutKind.Sequential)] 
    struct AStruct { }
    
    [StructLayout(LayoutKind.Sequential)]
    class B { AClass value; }
    
    [StructLayout(LayoutKind.Sequential)]
    class C<T> { T value; }
    
    class Program
    {
        static void M(object o) { Console.WriteLine(Marshal.SizeOf(o)); }
    
        static void Main()
        {
            M(new AClass());
            M(new AStruct());
            M(new B());
            M(new C<AStruct>());
            M(new C<AClass>());
        }
    }
    

    "Type 'C`1[AClass]' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed."
    

    为什么?具体来说,为什么SizeOf会堵塞 C<AClass> B C<AStruct> ?


    编辑: 因为这是在评论中被问到的,所以这是激发这个主要是学术问题的“现实世界”问题:

    C<T> 以及一个C#外部声明 M(C<T>) ,然后致电 M(C<int>) 在一条线上,以及 M(C<double>)

    2 回复  |  直到 16 年前
        1
  •  10
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    在任何互操作场景中都不支持泛型作为规则。如果您尝试封送泛型类型或值,P/Invoke和COM interop都将失败。因此,我预计 Marshal.SizeOf

        2
  •  0
  •   Peter Mortensen Pieter Jan Bonestroo    10 年前

    我认为你可以通过在字段“value”上设置MarshalAs属性来解决这个问题,指定最匹配的类型(例如,Unmanagedtype.SysInt)。请注意,它仍然不适用于所谓的不可映射类型(即字段偏移和大小不易推断的类型)。

    但是,AFAIK不建议在互操作中使用泛型。