为什么我们不能做在C#中的IntPtr和UIntPtr算术? [英] Why can't we do IntPtr and UIntPtr arithmetic in C#?

查看:681
本文介绍了为什么我们不能做在C#中的IntPtr和UIntPtr算术?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个看起来简单的问题:



由于本机大小的整数是最好的算法,为什么不C#(或任何其他.NET语言)与本地大小的IntPtr UIntPtr



支持算术

理想情况下,你可以写这样的代码:

 为(IntPtr的I = 1; I<改编。长度;我+ = 2)//arr.Length还应该返回IntPtr的
{
改编[我 - 1] + =改编[I] //随机的东西像这样
}



,以便它在32位工作和64位平台。 (目前,你必须使用






编辑



我的的使用这些作为指针(单词指针甚至没有被提到过)!它们可以只处理在C的本地INT 在MSIL和的C#对应使用intptr_t > stdint.h - 这是整数,不可以指针


解决方案
<。 p>在.NET 4中,键入的左手操作数的IntPtr 和整数类型(的右手操作数之间的算术 INT 等)的支持




以其他人说,他们的目的是代表本地语言指针(由名字的IntPtr暗示的那样)。权利要求你使用他们作为本地的整数,而不是指向它的罚款,但你不能忽视的一个整数的本土有史以来规模事项的主要原因之一是用作指针。如果您正在执行的数学运算,或独立于你的代码运行的处理器和内存架构等一般功能,它可以说是更有用,更直观的使用类型,如 INT ,你知道在任何情况下他们固定的大小和上下界,无论硬件。



正如型的IntPtr 旨在代表一个本地指针,算术运算被设计为代表,你会在一个指针进行逻辑数学运算:加一些整数偏移到本机指针达到一个新的原生指针(不是增加了两个的IntPtr s没有支持,并且也不是使用的IntPtr 为右手操作数)。


It's a simple-looking question:

Given that native-sized integers are the best for arithmetic, why doesn't C# (or any other .NET language) support arithmetic with the native-sized IntPtr and UIntPtr?

Ideally, you'd be able to write code like:

for (IntPtr i = 1; i < arr.Length; i += 2) //arr.Length should also return IntPtr
{
    arr[i - 1] += arr[i]; //something random like this
}

so that it would work on both 32-bit and 64-bit platforms. (Currently, you have to use long.)


Edit:

I'm not using these as pointers (the word "pointer" wasn't even mentioned)! They can be just treated as the C# counterpart of native int in MSIL and of intptr_t in C's stdint.h -- which are integers, not pointers.

解决方案

In .NET 4, arithmetic between a left hand operand of type IntPtr and a right hand operand of integer types (int, long, etc) is supported.

[Edit]: As other people have said, they are designed to represent pointers in native languages (as implied by the name IntPtr). It's fine to claim you're using them as native integers rather than pointers, but you can't overlook that one of the primary reasons the native size of an integer ever matters is for use as a pointer. If you're performing mathematical operations, or other general functions that are independent from the processor and memory architecture that your code is running on, it is arguably more useful and intuitive to use types such as int and long where you know their fixed size and upper and lower bounds in every situation regardless of hardware.

Just as the type IntPtr is designed to represent a native pointer, the arithmetic operations are designed to represent logical mathematical operations that you would perform on a pointer: adding some integer offset to a native pointer to reach a new native pointer (not that adding two IntPtrs is not supported, and nor is using IntPtr as the right hand operand).

这篇关于为什么我们不能做在C#中的IntPtr和UIntPtr算术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆