简体   繁体   中英

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(doit);
        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.

它用于定义给定类型的扩展方法

它用于标记要添加扩展方法的对象类型。

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.

ie: now you can do

Control myControl = new Control();

myControl.InvokeIfNeeded(myaction);

or

myControl.InvokeIfNeeded(myaction, args);

将“this”关键字添加到这样的参数将导致该方法被解释为Extension方法而不是常规静态方法。

方法声明中的this修饰符表示该方法是扩展方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM