繁体   English   中英

什么是“这个”用于?

[英]What's “this” used for?

我读了一些c#代码,无法理解函数参数中的“this”关键字? 有人可以告诉我它用于什么? 谢谢。

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);
    }
} 

它用于指定扩展方法操作的类型。 也就是说, public static void InvokeIfNeeded(this Control ctl, Action doit)将“ InvokeIfNeeded方法“添加”到Control类(以及所有派生类)。 但是,只有在将声明它们的类的命名空间显式导入范围时,才能使用此方法。

它表示扩展方法。 在您给出的示例中,任何Control对象都可以使用InvokeIfNeeded(Action doit)方法。 这是Control已有的所有方法的补充。

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

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

方法的静态声明和传入的this修饰符表示一个Extension方法,其中所有Control对象都将添加这些方法,就像它们最初以这种方式构建一样。

即:现在你可以做到

Control myControl = new Control();

myControl.InvokeIfNeeded(myaction);

要么

myControl.InvokeIfNeeded(myaction, args);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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