没有构造函数的C#类 [英] C# class without constructor

查看:816
本文介绍了没有构造函数的C#类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这怎么可能,在C#类可以定义没有构造?
比如说我有一个类

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



UPD:
我也可以这样定义一个类:

UPD: also I can define a class in this way:

internal class TextStyle
{
    internal string text = "";
    internal Font font = new Font("Arial", 18);
    internal Color color = Color.Red;

    public TextStyle()
        {
            text = "some other text";
            font = new Font("Arial", 8);
            color = Color.Black;
        }
}

和它编译好。但是,什么样的代码将首先执行?我将获得红色文字或黑白文本?

And it compiles well. But what code will be executed first? Will I get Red text or Black text?

推荐答案

如果你不申报非静态类中的任何构造函数,编译器提供了一个公共的(或受保护的抽象班)参数构造函数为您服务。你的类实际上有一个构造器:

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()
{
}

这是一节所述的C#4规范的10.11.4:

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.

唯一类在C#中不具有的任何的实例构造函数是静态类,它们的不能的有构造。

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

这篇关于没有构造函数的C#类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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