AddressOf替代在C# [英] AddressOf alternative in C#

查看:274
本文介绍了AddressOf替代在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能anyboby帮我在C#中关于VB6的 AddressOf运算符的替代解决方案? AddressOf返回一个long值。我能得到什么样的方式在C#中的输出?

Could anyboby help me with the alternative solution in C# regarding AddressOf operator in VB6? AddressOf returns a long value. What way can I get the output in C#?

推荐答案

拓展哈珀谢尔比的答案,肯定是可以做到的,但它通常是。一个代码味道这样做在.NET

Expanding on Harper Shelby's answer, yes it can be done, but it's generally a code smell to do so in .NET.

要获得在C#中的变量的地址,你可以使用C风格的指针(*)/地址(安培; )/解引用( - >)语法。为了做到这一点,你必须编译与/不安全编译器开关的应用程序,因为你一旦你开始处理直接内存地址弹跳出来的托管代码的安全网。

To get the address of a variable in C#, you can use C-style pointer (*) /address (&) / dereference (->) syntax. In order to do this, you will have to compile the app with the /unsafe compiler switch, as you're bouncing out of the safety net of managed code as soon as you start dealing with memory addresses directly.

从MSDN样本最讲述的故事:

The sample from MSDN tells most of the story:

int number;
int* p = &number;
Console.WriteLine("Value pointed to by p: {0}", p->ToString());

这分配数量变量的地址指针到一个-INT p

This assigns the address of the number variable to the pointer-to-an-int p.

有一些捕捉到这一点:


  1. 的变量,其地址你取必须初始化。而不是一个值类型,默认情况下的问题,但它是引用类型的问题。

  2. 在.NET中,变量可以在内存中移动没有你意识到这一点。如果你需要处理一个变量的地址,你真的想使用 固定 引脚在RAM中的变量

  3. &放大器。只能应用于变量,而不是一个常数也没有的值。 (换句话说,你不能使用像为int * p =&放一个结构; GetSomeInt();

  4. 同样,你的代码必须在不安全模式下,它的标志,你将使用托管代码以外的功能CLR安全网。

  1. The variable whose address you are fetching must be initialized. Not a problem for value types, which default, but it is an issue for reference types.
  2. In .NET, variables can move in memory without you being aware of it. If you need to deal with the address of a variable, you really want to use fixed to pin the variable in RAM.
  3. & can only be applied to a variable, not a constant nor a value. (In other words, you cannot use a construct like int* p = &GetSomeInt();)
  4. Again, your code must be compiled in unsafe mode, which flags the CLR that you will be using features outside the managed code "safety net."

一般编译,我在这个世界上的建议是要认真考虑的为什么的你认为你需要做这在.NET世界。一个.NET的任务是从逆着金属屏蔽层的开发,而这个功能是反这一使命。它存在需要它的那些(罕见)的情况;如果可能的话,如果你发现自己轻率使用这只是因为你可以,你可能误用它,并引入码味。

Generally, my advice in this world is to seriously consider why you think you need to do this in the .NET world. One of .NET's missions was to shield developers from going against the metal, and this feature is counter to that mission. It exists for those (rare) scenarios where it is needed; if you find yourself frivolously using this simply because you can, you're probably mis-using it and introducing code smell.

避免它,但知道如何使用它,如果你绝对必须。

Avoid it if possible, but know how to use it if you absolutely must.

这篇关于AddressOf替代在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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