AddressOf alternative in C#

2019-02-17 05:06发布

问题:

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#?

回答1:

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:

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

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

There are some catches to this:

  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."

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.



回答2:

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.



回答3:

Apparently, this can be done (though I'm not sure where you'd need it). Here's the MSDN page.



回答4:

EventHandler handler1 = this.button1_Click;
EventHandler handler2 = new EventHandler( this.button1_Click );
...
...
...
void button1_Click( object sender, EventArgs e ){
    // ....
}

Both notation are equivalent.