C#.NET IntPtr 无效类型

标签 c# intptr

private string getLngLat(string strLAC, string strCID)
    {
        string str;
        try
        {
            HttpWebRequest length = (HttpWebRequest)WebRequest.Create(new Uri("http://www.google.com/glm/mmap"));
            length.Method = "POST";
            int num = Convert.ToInt32(strLAC);
            byte[] numArray = AjaxFrm.PostData(num, Convert.ToInt32(strCID));
            length.ContentLength = (long)((int)numArray.Length);
            length.ContentType = "application/binary";
            length.GetRequestStream().Write(numArray, 0, (int)numArray.Length);
            HttpWebResponse response = (HttpWebResponse)length.GetResponse();
            byte[] numArray1 = new byte[checked((IntPtr)response.ContentLength)]; // ERROR AT HERE
            response.GetResponseStream().Read(numArray1, 0, (int)numArray1.Length);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                str = string.Format("Error {0}", response.StatusCode);
            }
            else
            {
                byte num1 = numArray1[0];
                byte num2 = numArray1[1];
                byte num3 = numArray1[2];
                if ((numArray1[3] << 24 | numArray1[4] << 16 | numArray1[5] << 8 | numArray1[6]) != 0)
                {
                    str = "";
                }
                else
                {
                    double num4 = (double)(numArray1[7] << 24 | numArray1[8] << 16 | numArray1[9] << 8 | numArray1[10]) / 1000000;
                    double num5 = (double)(numArray1[11] << 24 | numArray1[12] << 16 | numArray1[13] << 8 | numArray1[14]) / 1000000;
                    str = string.Format("{0}&{1}", num5, num4);
                }
            }
        }
        catch (Exception exception)
        {
            str = string.Format("Error {0}", exception.Message);
        }
        return str;
    }

byte[] numArray1 = new byte[checked((IntPtr)response.ContentLength)];

这里我得到了错误

错误 3 无法将类型“System.IntPtr”隐式转换为“int”。存在显式转换(您是否缺少强制转换?)

怎么会出现这个错误呢?怎么解决?

最佳答案

直接指定数组长度即可,无需先尝试转换为IntPtr:

byte[] numArray1 = new byte[response.ContentLength];

IntPtr 是一种仅用于保存指针值的类型,因此整数类型的通常规则不适用。指针值不是合理的数组长度,因此语言设计者不允许使用 IntPtr 来指定数组长度。

关于C#.NET IntPtr 无效类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18224202/

相关文章:

c# - 检测它是否是应用程序的最后一个实例 c#

c# - Gremlin.Net 从 Enumerable.SelectIListIterator 对象转换为真实类型

c# - 从 C# 函数在 C++ COM dll 中传递字符串

c# - IntPtr 究竟是什么?

c# - 将 IntPtr 转换为 C# 结构指针

c# - handle 有什么用?指针

c# - 如何在 C# 中将位图图像转换为 IntPtr?

c# - 循环遍历 DataRow 中的每个元素

c# - 在 visual studio 中使用 Skype4COM.dll COM API

c# - 笔记本电脑/台式机 sleep 事件