简体   繁体   English

为什么我可以在C#中执行此操作?(带有()的公共类

[英]Why can i do this in C#?(public class with ())

In C# why am I able to compile and run a program with the following code 在C#中,为什么我能够使用以下代码编译和运行程序

public class HammingTFTP()
{
     //class variables here
     public HammingTFTP(string mode, string host, string fileName)
           :this()
     {
        //code here
     }
}

I am coding on a mac and running mono 3.6.0. 我在mac上编码并运行mono 3.6.0。 I understand there should be no () after the class declaration and i should remove :this(). 我明白在类声明之后应该没有(),我应该删除:this()。 Just wondering why this compiles and runs in the first place. 只是想知道为什么这个编译并运行在第一位。 Could it be a bug with the given version of mono? 这可能是给定版本的单声道的错误吗?

This doesn't compile with the .NET compiler, but it does with the Roslyn compiler. 这不能用.NET编译器编译,但它与Roslyn编译器一起编译。 Demo: https://dotnetfiddle.net/HkngI3 演示: https//dotnetfiddle.net/HkngI3

This is a C# 6.0 feature called "Primary Constructors". 这是一个名为“Primary Constructors”的C#6.0功能。 See The New and Improved C# 6.0 请参阅新增和改进的C#6.0

It allows you to declare a primary constructor for the class alongside its declaration, such as: 它允许您在声明旁边声明类的主要构造函数,例如:

public class MyClass(string name)
{
    public string Name {get; } = name;  
}

Mono 3.6.0 already supports some of the features that will come in C# 6.0, as stated here . 单3.6.0已经支持了一些认为会在C#6.0,如规定的功能在这里

In your case this is namely primary constructors. 在你的情况下,这是主要的构造函数。 See this language preview for more details. 有关详细信息,请参阅此语言预览

Without using primary constructors, your code would translate as follows: 如果不使用主构造函数,您的代码将转换如下:

public class HammingTFTP
{
    // generated via primary constructor
    public HammingTFTP()
    {
    }

    //class variables here
    public HammingTFTP(string mode, string host, string fileName)
       :this()
    {
       //code here
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM