基地()和()这个构造的最佳实践 [英] base() and this() constructors best practices

查看:118
本文介绍了基地()和()这个构造的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在什么情况下我应该做的:基地()和:这个()以下我的构造函数的括号中调用构造函数(甚至在code等地)。当这些调用好的做法和他们是强制性的时候?

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.

即使有一个默认的构造函数,你可能仍想调用不同的构造比默认的构造函数。在这种情况下,你可能仍然希望使用基地(富,吧)来调用不同的构造比基本构造。

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.

我不认为这是一个不好的做法,忽略基地()时,你要调用基类的默认构造函数,但如果你想成为明确我看到它包括没有坏处。这是一个品味的问题。

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.

时,它可以是非常有用的一个例子是在构造重用通用code。例如,在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.

重用code在构造函数中的另一种方法是将其因素伸到它是由希望使用它每个构造称为静态函数。

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.

这篇关于基地()和()这个构造的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆