base() 和 this() 构造函数最佳实践 [英] base() and this() constructors best practices
问题描述
在什么条件下我应该在我的构造函数的括号之后(或者甚至在代码的其他地方)调用 :base()
和 :this()
构造函数调用).这些电话什么时候是好的做法,什么时候是强制性的?
Under what conditions am I supposed to make the :base()
and :this()
constructor calls following my constructor's parentheses (or even in other places in the code). When are these calls good practices and when are they mandatory?
推荐答案
: base(...)
如果省略对基构造函数的调用,它将自动调用默认的基构造函数.
If you omit the call to a base constructor it will call the default base constructor automatically.
如果没有默认构造函数,则必须显式调用基构造函数.
It is mandatory to call a base constructor explicitly if there is no default constructor.
即使有默认构造函数,您可能仍然希望调用与默认构造函数不同的构造函数.在这种情况下,您可能仍然希望使用 base(foo, bar)
来调用与基本构造函数不同的构造函数.
Even if there is a default constructor you may still wish to call a different constructor than the default constructor. In this case you may still wish to use base(foo, bar)
to call a different constructor than the base constructor.
我不认为在您想调用基类默认构造函数时省略 base()
是一种不好的做法,尽管如果您喜欢明确我认为包括它.这是一个品味问题.
I do not consider it to be a bad practice to omit base()
when you want to call to the base class default constructor, although if you like to be explicit I see no harm in including it. It is a matter of taste.
: this(...)
此语法允许您在同一类中调用具有不同签名的构造函数.这样做从来不是强制性的,但有时会很有用.
This syntax allows you to call one constructor with a different signature from another within the same class. It is never mandatory to do this, but can sometimes be useful.
一个有用的例子是在构造函数中重用公共代码.例如,在 C# 3.5 或更早版本中,您可能希望在构造函数上模拟可选参数:
An example of when it can be useful is for reusing common code in the constructors. For example in C# 3.5 or before you may want to simulate optional parameters on a constructor:
Foo(int x, int y)
{
this.x = x;
this.y = y;
}
Foo(int x) : this(x, 10) {} // y defaults to 10
现在可以使用 C# 4.0 可选参数,这减少了对这种方法的需求.
With C# 4.0 optional parameters are now available which reduces the need for this approach.
在构造函数中重用代码的另一种方法是将其分解为一个静态函数,该函数由每个希望使用它的构造函数调用.
An alternative way to reuse code in constructors is to factor it out into a static function which is called from each constructor that wishes to use it.
这篇关于base() 和 this() 构造函数最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!