Yesterday, I wrote a program about Socket to receive the UDP package. The socket.receiveFrom method was called. I found a problem with the REF and OUT parameters. Here, discussed together, first declare, the following conclusions It is a speculation that it has not yet been given, if there is a mistake, please correct it.
First, the prototype of the ReceiveFrom method is
Public int respientFrom (byte [], ref endpoint;
There is an endpoint parameter for REF, with it to return the source address information of the received package, the semantics of the REF is the pass reference, that is, the modification of the collected reference can be reflected outside the method. I usually use ipendpoint to represent address information, so I naturally use the following call method.
(Code 1)
IpendPoint IEP = New IpendPoint (ipaddress.any, 0);
Socket.ReceiveFrom (Buffer, Ref (Endpoint) IEP);
At this time, there is an error in compile, "" REF or OUT parameters must be a LVALUE ", how will IEP not a left value? The key is to change the forced conversion (for example (endpoint) IEP) when calling the method, I changed the code.
(Code 2)
IpendPoint IEP = New IpendPoint (ipaddress.any, 0);
Endpoint EP = (endpoint) IEP;
Socket.ReceiveFrom (Buffer, Ref (Endpoint) IEP);
This time it was compiled. Why do you have problems when you call? Here, you should consider a detail of the type forced conversion. Forced conversion, the compiler will become a temporary reference, and then pass this temporary reference to a reference to the same type, this temporary reference is special - not a left value (LVALUE), can not be assigned! The method of using the REF parameters generally makes modifications to this reference. If this temporary reference is passed directly, the compiler will complain that the REF or OUT parameter must be a LValue. Code 2 first assigns this temporary reference to a regular reference, then this regular reference is copyable.