: C# 构造函数中的 this(foo) 语法?
我时不时地会遇到以前见过但从未使用过的语法。 这是其中之一。
有人可以解释 C# 构造函数方法后“:this”或“:base”的用途吗?
例如:
public MyClass(SomeArg arg) : this(new SomethingElse(), arg)
{
}
我的直觉是它用于将默认参数映射到另一个构造函数方法。
Every now and then, I bump into syntax that I've seen before, but never used. This is one of those times.
Can someone explain the purpose of ":this" or ":base" following a C# constructor method?
For example:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(7)
你的直觉是对的。 该语法用于调用同一类中的重载构造函数:
public class Test
{
public Test() : this("Called from default constructor") { }
public Test(String msg)
{
Console.WriteLine(msg);
}
}
以下代码:
public static void Main(String[] args)
{
Test t1 = new Test();
Test t2 = new Test("Called from Main function");
}
输出以下内容
Called from default constructor Called from main function
类似地, : base(someParams)
用于调用基构造函数。
.NET 类中的每个构造函数都确保它所继承的类中的构造函数也被调用。
因此,如果您有以下类:
public class Base { }
public class Something : Base { }
public class Else : Something { }
那么 Else 中的构造函数将调用 Something 中的构造函数,Something 还将调用 Base 中的构造函数。
在基类(即您的后代)中调用的构造函数始终是无参数构造函数。
如果您没有,或者想要覆盖它,您可以通过指定基础(此处的一些参数)来覆盖它。 这将在基类中选择正确的构造函数。
您还可以要求构造函数首先调用同一类中同一级别的另一个构造函数。 这可用于避免在多个构造函数中重复构造函数代码。 但最终,被调用的构造函数将调用基类中的构造函数。
我希望这是可以理解的。
如果我没记错的话,情况是这样的:
public MyClass(SomeArg arg) : this(new SomethingElse(), arg)
会打电话
public MyClass(SomethingElse arg, SomeArg arg1) : base or this or nothing
,一直持续到你有基地或什么也没有。
如果你有base(....)
,那么该构造函数将使用给定的参数(如果有)调用基本构造函数,而该参数又可以委托给它自己的构造函数(同一个游戏)。
如果没有任何内容,则会自动调用基类的无参数构造函数。
使用 this(....)
后,将使用与参数匹配的构造函数并执行其主体 - 除了已使用 this(. ...)
。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
你基本上是对的。
this()
在当前实例上调用构造函数,base()
在当前实例上调用超类型的构造函数。 它们通常用于处理构造函数重载,因此您可以添加其他选项,而无需将其分解为单独的方法。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.