【问题标题】:This keyword in some case not clear [duplicate]这个关键字在某些情况下不清楚[重复]
【发布时间】:2013-05-09 03:27:50
【问题描述】:

当我进行编码时,我遇到了这样的函数 =>

public RelayCommand(Action<object> execute): this(execute, null)

我真的不知道这里的“this”关键字用法

【问题讨论】:

  • this 在这种情况下通常意味着使用这些参数调用 this 类的另一个构造函数。这是一种减少代码重复的方法

标签: c#


【解决方案1】:

这是构造函数链接。 this(execute, null) 调用该类中定义的另一个构造函数,该构造函数采用 Action&lt;object&gt; 和其他一些值。例如:

class Whatever
{
    public Whatever() : this("string arg") {}  // calls Whatever(string)

    public Whatever(string something) {}
}

【讨论】:

    【解决方案2】:

    this 关键字的这种特殊用法让您可以从另一个构造函数调用一个构造函数,大概是为了提供一个默认参数。您可以通过应用默认参数值将两个构造函数“折叠”为一个:

    public RelayCommand(Action<object> execute, string name = null) {
        ...
    }
    

    【讨论】:

      【解决方案3】:

      这是指当前构造函数的重载版本。 基本上这两个构造函数是链接在一起的,这有助于避免构造函数中的重复代码

      【讨论】:

        猜你喜欢
        • 2017-06-21
        • 2011-07-22
        • 2016-01-27
        • 1970-01-01
        • 2020-06-20
        • 1970-01-01
        • 2010-12-31
        • 2013-04-16
        • 1970-01-01
        相关资源
        最近更新 更多