I'm curious about this code snippet:
public static cla开发者_如何学JAVAss XNAExtensions
{
/// <summary>
/// Write a Point
/// </summary>
public static void Write(this NetOutgoingMessage message, Point value)
{
message.Write(value.X);
message.Write(value.Y);
}
// ...
};
What does the this
keyword mean next to the parameter type? I can't seem to find any information about it anywhere, even in the C# specification.
That's an extension method.
The syntax means you can call the method as if it was a member of the NetOutgoingMessage class:
var msg = new NetOutgoingMessage();
msg.Write(somePoint);
This is basically rewritten by the compiler to:
var msg = new NetOutgoingMessage();
XNAExtensions.Write(msg, somePoint);
It's just nice syntactical sugar.
That is how an extension method is defined.
What this essentially means is that, even though this method is contained in an encapsulating static class, when using the type specified (in the extension method parameters labelled this
) such a method will be automatically exposed such that:
var typeInstance = new TypeWithExtensionMethod();
typeInstance.ExtensionMethod(anyParametersRequiredButNotTypeInstance);
Is possible, as opposed to:
var type = new TypeWithExtensionMethod();
ExtensionMethods.ExtensionMethod(typeInstance, anyOtherParametersRequired);
What does the this keyword mean next to the parameter type?
It means the method is an extension method.
I can't seem to find any information about it anywhere, even in the C# specification.
The information you seek is in section 10.6.9 of the C# 4 specification.
It indicates that Write
is an extension method to the NetOutgoingMessage
class.
It means it is an extension method. MSDN
It's extension method for NetOutgoingMessage
class.
See here: link text
It means that you are passing the reference of the variable. If you assign the returned value to new variable - both the new and the passed variable when calling the method will be the same because inside the method you are changing the passed variable.
精彩评论