运算符+在不安全的非管理C#代码中 [英] Operator + in unsafe unmanage C# code

查看:88
本文介绍了运算符+在不安全的非管理C#代码中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c#中有这样的代码:



char * length =(char *)value.Length;

char * chPtr =(char *)startIndex;

char * chPtr2 =(char *)count;



//错误

if((chPtr + length)< = chPtr2)

{}



如果条件与运营商+错误



你可以帮我吗



我尝试过:



if((chPtr)+(length))< = chPtr2)

{}

解决方案

< blockquote>嗯...那里有几个古怪的东西。

startIndex 听起来不像指针 - 它听起来像一个整数索引到某种形式的内存结构:数组或类似的。

您还将一个长度转换为一个奇怪的指针。

但是当你找到显示错误的代码时:

  if ((chPtr + length)<  = chPtr2) )

你告诉编译器要做的是将 chPtr 添加到 length :并且他们都被声明为指针:

 char * length =(char *) value  .Length; 
char * chPtr =(char *)startIndex;

这意味着你告诉编译器添加两个指针 - 这不会产生任何有用的东西,但肯定不会产生另一个指针。根据DateTime来考虑它:如果你减去两个DateTime值,你会得到一个Timespan--两个日期之间的差异。如果减去两个指针,则得到整数(或长整数) - 两个指针值之间的字节数。但是如果你添加两个DateTimes,你会得到什么?没什么用的。这同样适用于指针 - 添加它们不会产生任何有用的东西!



我认为这三个值中的任何一个都不应该是指针!

这是来自Microsoft官方的c#站点。



为了保持类型的安全性和安全性,默认情况下C#不支持指针算法。但是,通过使用unsafe关键字,您可以定义可以使用指针的不安全上下文。有关指针的更多信息,请参阅指针类型主题。


i have code in c# like this :

char* length = (char*) value.Length;
char* chPtr = (char*) startIndex;
char* chPtr2 = (char*) count;

//Error
if ((chPtr + length) <= chPtr2)
{}

if condition with operator + ERROR

can you help me

What I have tried:

if ((chPtr) + (length)) <= chPtr2)
{}

解决方案

Um...there are a couple of oddities there.
startIndex doesn't sound like a pointer - it sounds like an integer which indexes into a memory structure of some form: an array or similar.
You are also converting a Length to a pointer which is going to be odd.
But when you get to your code that shows the error:

if ((chPtr + length) <= chPtr2))

What you are telling the compiler to do is add chPtr to length: and they are both declared as pointers:

char* length = (char*) value.Length;
char* chPtr = (char*) startIndex;

Which means you are telling the compiler to add two pointers - which doesn't produce anything useful, but certainly doesn't produce another pointer. Think of it in terms of DateTime: if you subtract two DateTime values, you get a Timespan - the difference between the two dates. If you subtract two pointers, you get in integer (or long) - the number of bytes between the two pointer values. But if you add two DateTimes, what do you get? Nothing useful. The same applies to pointers - adding them doesn't produce anything useful!

I don't think any of those three values should be pointers at all!


This is from Microsoft official c# site.

To maintain type safety and security, C# does not support pointer arithmetic, by default. However, by using the unsafe keyword, you can define an unsafe context in which pointers can be used. For more information about pointers, see the topic Pointer types.


这篇关于运算符+在不安全的非管理C#代码中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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