:在C#构造函数这个(富)语法?语法、函数

2023-09-03 00:22:36 作者:再痛丶也要坚持

然后每一个现在,我碰到,我已经看到过,但从来没有使用过的语法。这是那个时代的一个。

Every now and then, I bump into syntax that I've seen before, but never used. This is one of those times.

一个人能解释的目的::基地,这个或?下一个C#构造函数方法

Can someone explain the purpose of ":this" or ":base" following a C# constructor method?

例如:

public MyClass(SomeArg arg) : this(new SomethingElse(), arg)
{
}

我的直觉是,它是用于映射默认参数到另一个构造方法。

My gut feeling is that it is used to map a default argument onto another constructor method.

推荐答案

您是基本正确的。 这个()要求在当前实例的构造,基()调用父类型的构造函数的当前实例。他们通常用来处理构造函数重载,所以你可以不打破东西出来变成一个独立的方法添加额外的选项。

You're basically right. this() calls a constructor on the current instance, base() calls the supertype's constructor on current instance. They're generally used to handle constructor overloads so you can add additional options without breaking things out into a separate method.