空的构造函数或没有构造 [英] Empty constructor or no constructor
问题描述
我觉得是不是强制性的在一个类(C#)默认构造函数。
因此,在这种情况下,我将有一个空构造类或我可以跳过它?
时它最佳实践有一个默认的空构造?
类测试
{
公开测试()
{
}
......
}
或
类测试
{
......
}
如果该类不会由第三方使用,并且你不需要一个重载的构造函数,不写一个空的构造。
不过...
假设你已经发货的产品,和第三方使用你的类。几个月后,有一个新的要求,让你添加一个构造函数的参数。
现在,通过这样做,C#编译器不再生成默认构造函数。如果你不明确添加一个空的构造,第三方代码将休息。
在我看来,你应该总是定义公共空构造函数(单行)第三方使用的类。
I think it is not mandatory to have a default constructor in a class (C#).
So in that situation shall I have a empty constructor in the class or I can skip it?
Is it a best practice to have a default empty constructor?
Class test
{
public test()
{
}
......
}
or
Class test
{
......
}
If the class won't be used by third parties and you don't need an overloaded constructor, don't write an empty constructor.
But...
Imagine you already shipped the product, and third parties use your class. A few months later there's a new requirement that makes you add a constructor with an argument.
Now, by doing so, the C# compiler no longer generates a default constructor. If you don't add an empty constructor explicitly, the third party code will be break.
In my opinion, you should always define empty constructors (one liner) for public classes used by third parties.
这篇关于空的构造函数或没有构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!