构造函数括号前面的“This”关键字 - C# [duplicate]

the "This" keyword front of constructor parentheses - C# [duplicate]

提问人:DeadDreams 提问时间:1/14/2023 更新时间:1/14/2023 访问量:63

问:

我知道“这个”关键字以及它的工作原理。但这有什么用呢?

public ReactiveProperty() : this(default(T))
{

}

我在 UniRx 项目中看到了这一点。我只是不知道构造函数前面的“This”关键字。 我用谷歌搜索了一下,但没有什么可捕捉的。 有人知道吗?

C# 构造函数 This Unirx

评论


答:

1赞 Guru Stron 1/14/2023 #1

此语法用于调用类中定义的另一个构造函数。文档中的示例:

class Coords
{
    public Coords() : this(0, 0) // calls Coords(int x, int y) with x = 0 and y = 0
    {  }

    public Coords(int x, int y)
    {
        X = x;
        Y = y;
    }

    public int X { get; set; }
    public int Y { get; set; }

    public override string ToString() => $"({X},{Y})";
}
var p1 = new Coords();
Console.WriteLine($"Coords #1 at {p1}");
// Output: Coords #1 at (0,0)

var p2 = new Coords(5, 3);
Console.WriteLine($"Coords #2 at {p2}");
// Output: Coords #2 at (5,3)

评论

0赞 DeadDreams 1/14/2023
谢谢人。我参与了好几天。我不知道它是什么,要正确搜索它。
0赞 Guru Stron 1/14/2023
@DeadDreams很高兴帮忙!至于关闭 - 你不必担心,它无论如何都不是针对你的,并不意味着你应该知道要搜索什么,它只是意味着你的问题在另一个问题中有答案(正如标题所说)。