开发者

What's "this" used for?

I read some c# codes and can not understand the "this" key word in the function parameter? Could somebody tell me what it is used for? Thanks.

public static class ControlExtensions
{
    public static void InvokeIfNeeded(this Control ctl,
        Action doit)
    {
        if (ctl.InvokeRequired)
            ctl.Invoke(d开发者_开发百科oit);
        else
            doit();
    }

    public static void InvokeIfNeeded<T>(this Control ctl,
        Action<T> doit, T args)
    {
        if (ctl.InvokeRequired)
            ctl.Invoke(doit, args);
        else
            doit(args);
    }
} 


It's used to specify a type on which the extension method operates. That is, public static void InvokeIfNeeded(this Control ctl, Action doit) "adds" an InvokeIfNeeded method to Control class (and all derived classes). This method, however, can only be used if you explicitly import the namespace of a class they are declared in into your scope.


It signifies an extension method. In the example you gave, any Control object will have the method InvokeIfNeeded(Action doit) available to use. This is in addition to all the methods that a Control already has.


It is used to define an extension method for a given type.


the static declaration of the method and the this modifier passed in signifies a Extension method where all Control objects will have these methods added on as if they were initially built that way.

i.e: now you can do

Control myControl = new Control();

myControl.InvokeIfNeeded(myaction);

or

myControl.InvokeIfNeeded(myaction, args);


It is used to mark the type of object that the extension method is being added to.


Adding the 'this' keyword to a parameter like this will cause the method to be interpretted as an Extension method rather than a regular static method.


The this modifier in a method declaration signifies that the method is an extension method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜