C# 中的 AddressOf 替代方案
Anyboby 可以帮我找到有关 VB6 中的 AddressOf 运算符 的 C# 替代解决方案吗? AddressOf 返回一个长整型值。 我怎样才能得到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#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C# 有特殊的语法用于将函数分配给委托/事件。 只需使用; +=;
如果您实际上试图获取该地址用于其他用途,那么您就不走运了。 关于托管代码的问题之一是这些地址不一定是固定的。 虽然大多数功能不太可能改变,但在某些情况下这是可能的。
C# has special syntax for assigning functions to delegates/events. Just use
<delegate> += <function>;
If you're actually trying to get the address for some other use, you're out of luck. One of the things about managed code is that these addresses aren't necessarily fixed. While it would be unlikely that most functions would ever change there are circumstances where it's possible.
显然,这是可以做到的(尽管我不确定你在哪里需要它)。
这是 MSDN 页面。
Apparently, this can be done (though I'm not sure where you'd need it).
Here's the MSDN page.
两种表示法是等效的。
Both notation are equivalent.
扩展 Harper Shelby 的答案,是的,可以做到,但在 .NET 中这样做通常会产生代码味道。
要在 C# 中获取变量的地址,可以使用 C 风格的指针 (*) /地址 (&) / 取消引用 (->) 语法。 为此,您必须使用 /unsafe 编译器开关来编译应用程序,因为一旦开始直接处理内存地址,您就会跳出托管代码的安全网。
MSDN 中的示例讲述了大部分内容:
这将
number
变量的地址分配给指向 intp
的指针。对此有一些注意事项:
已修复
以将变量固定在 RAM 中。int* p = &GetSomeInt();
这样的构造)一般来说,我对这个世界的建议是认真考虑为什么你认为你需要在.NET世界中这样做。 .NET 的使命之一是保护开发人员免受金属侵害,而此功能与该使命背道而驰。 它的存在是为了那些需要它的(罕见的)场景; 如果您发现自己只是因为可以而轻率地使用它,那么您可能误用了它并引入了代码气味。
如果可能,请避免使用它,但如果绝对必要,请知道如何使用它。
Expanding on Harper Shelby's answer, yes it can be done, but it's generally a code smell to do so in .NET.
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.
The sample from MSDN tells most of the story:
This assigns the address of the
number
variable to the pointer-to-an-intp
.There are some catches to this:
fixed
to pin the variable in RAM.int* p = &GetSomeInt();
)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.