Delphi的"ZeroMemory"相当于什么?在C#中? [英] What is the equivalent of Delphi "ZeroMemory" in C#?

查看:63
本文介绍了Delphi的"ZeroMemory"相当于什么?在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在delphi的"ZeroMemory"过程中,要求输入两个参数.

In delphi the "ZeroMemory" procedure, ask for two parameters.

代码示例

procedure ZeroMemory(Destination: Pointer; Length: DWORD);
begin
 FillChar(Destination^, Length, 0);
end;

我想做到这一点,或在C#中做到类似...所以,它们的等效物是什么?

I want make this, or similar in C#... so, what's their equivalent?

提前谢谢!

推荐答案

.NET框架对象始终被初始化为已知状态

.NET框架的值类型会自动归零"-这意味着该框架保证在将其返回给您使用之前,将其初始化为其自然的默认值.由值类型(例如数组,结构,对象)组成的事物的字段也进行了类似的初始化.

.NET framework objects are always initialized to a known state

.NET framework value types are automatically 'zeroed' -- which means that the framework guarantees that it is initialized into its natural default value before it returns it to you for use. Things that are made up of value types (e.g. arrays, structs, objects) have their fields similarly initialized.

通常,在.NET中,所有托管对象都被初始化为默认值,并且从来没有像其他对象那样无法预测对象的内容(因为它包含的数据恰好位于该特定内存位置中)非托管环境.

In general, in .NET all managed objects are initialized to default, and there is never a case when the contents of an object is unpredictable (because it contains data that just happens to be in that particular memory location) as in other unmanaged environments.

答案:您不需要这样做,因为.NET会自动为您将对象清零".但是,您应该知道每种值类型的默认值是什么.例如, bool 的默认值为false,而 int 的默认值为零.

Answer: you don't need to do this, as .NET will automatically "zero" the object for you. However, you should know what the default value for each value type is. For example, the default of a bool is false, and the default of an int is zero.

通常仅在与外部非托管库互操作时才需要对存储区域进行归零".

"Zero-ing" a region of memory is usually only necessary in interoping with external, non-managed libraries.

如果您有一个固定的指向存储区域的指针,该存储区域包含要传递给外部非托管库的数据(例如,用C编写),并且您想将该存储区清零,则您的指针最多可能指向字节数组,您可以使用简单的for循环将其归零.

If you have a pinned pointer to a region of memory containing data that you intend to pass to an outside non-managed library (written in C, say), and you want to zero that section of memory, then your pointer most likely points to a byte array and you can use a simple for-loop to zero it.

另一方面,如果在.NET中分配了一个大对象,请尝试重用它,而不是将其丢弃并分配一个新对象.这是因为.NET框架会自动将任何新对象置零",对于大型对象,这种清除将导致性能下降.

On the flip side, if a large object is allocated in .NET, try to reuse it instead of throwing it away and allocating a new one. That's because any new object is automatically "zeroed" by the .NET framework, and for large objects this clearing will cause a hidden performance hit.

这篇关于Delphi的"ZeroMemory"相当于什么?在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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