C# class without constructor

2019-03-11 04:48发布

How is it possible that class in C# may has no constructors defined? For instance I have a class

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();

1条回答
Bombasti
2楼-- · 2019-03-11 05:27

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:

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 is public.

The only classes in C# which don't have any instance constructors are static classes, and they can't have constructors.

查看更多
登录 后发表回答