public   struct   Person 

public   string   id; 
public   Intptr[]   id2=new   Intptr[12]; 

我想定义id2为一个固定长度的数组,我该怎么办?

解决方案 »

  1.   

    除非用 unsafe ,否则不能定义定长数组
      

  2.   

    数组不就是定长的吗?public struct Person  
    {  
    public string id;  
    public Intptr[] id2=new Intptr[12];  
    }  这样应该可以啊。
      

  3.   

    结构里面不允许设置数组,你可以在外面设置数组长度public struct Person   
    {   
    public string id;   
    public static Intptr[] id2;
    }   Person.id2 = new Intptr[12]; 
      

  4.   

    具体应用场景是什么?一般情况不推荐用 unsafe 的,而且有限制。
    你的写法,只要保证不去修改 id2 对象,也可以当定长来用的。
      

  5.   


    不修改id2的值,只是用其里面的值,如何用unsafe?定义定长?
      

  6.   

    那你之前的代码不能用吗?
    刚看了下定长数组不适用于 IntPtr
      

  7.   


        public struct Person
        {
            public string id;
            public IntPtr[] id2;
        }     class Program
        {
            static void Main(string[] args)
            {
                Person p = new Person();
                p.id2 = new IntPtr[12];
            }
        }完全没必要加static
      

  8.   


    我在用PtrToStructure时仍提示:数组运行时类型和元素中记录的子类型之间出现不匹配
      

  9.   

    重述一下问题:c#调用vc里的一个ocx
    ocx中有个结构
    struct{
    int nWnd;
    HWND ar[30];
    }mySt;ocx提供一个接口GetWnd()该接口返回的是mySt的结构指针在c#里调用GetWnd后获得指针,我想把结构里的值都读出来
    所以在c#里也定义了个同样的结构,于是出现了上述问题不知道整个思路对不?
      

  10.   

    人家是 int nWnd
    你干嘛要用string
      

  11.   

    果然是这样……
    那就是 unsafe 的定长数组了http://msdn.microsoft.com/zh-cn/library/zycewsya.aspx不过这个不支持 IntPtr ,你只能用基本类型再自己转。
      

  12.   

    抱歉,链接:http://msdn.microsoft.com/zh-cn/library/zycewsya.aspx
      

  13.   

    话说,有指针的话难道不是应该是 unsafe 的吗?
      

  14.   

    使用MarshalAs属性,
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
      

  15.   

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]  
    public int[] test;  
      

  16.   

    对大家的帮助,我感激的要哭!!!分少了,见笑了evilant
    的方法直接感谢同志么的链接、回复、指导!再次感谢
      

  17.   

    在.NET 4.0以后,微软会尽量解决掉这个属性