没有构造函数的C#类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9274573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# class without constructor
提问by TOP KEK
How is it possible that class in C# may has no constructors defined? For instance I have a class
C# 中的类怎么可能没有定义构造函数?例如我有一个类
internal class TextStyle
{
internal string text = "";
internal Font font = new Font("Arial", 8);
internal Color color = Color.Black;
}
And in the code this class is instantiated as
在代码中这个类被实例化为
TextStyle textParameters = new TextStyle();
采纳答案by Jon Skeet
If you don't declare any constructors for a non-static class, the compiler provides a public (or protected for abstract classes) parameterless constructor for you. Your class effectively has a constructor of:
如果您没有为非静态类声明任何构造函数,编译器会为您提供一个公共(或受保护的抽象类)无参数构造函数。你的类实际上有一个构造函数:
public TextStyle()
{
}
This is described in section 10.11.4 of the C# 4 spec:
这在 C# 4 规范的第 10.11.4 节中有描述:
If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class. If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs. If the class is abstract, then the declared accessibility for the default constructor is
protected. Otherwise, the declared accessibility for the default constructor ispublic.
如果类不包含实例构造函数声明,则会自动提供默认实例构造函数。该默认构造函数只是调用直接基类的无参数构造函数。如果直接基类没有可访问的无参数实例构造函数,则会发生编译时错误。如果类是抽象类,则默认构造函数的声明可访问性为
protected。否则,默认构造函数的声明可访问性为public。
The only classes in C# which don't have anyinstance constructors are static classes, and they can'thave constructors.
C# 中唯一没有任何实例构造函数的类是静态类,它们不能有构造函数。

