简体   繁体   English

C#中没有()的类初始化

[英]Class initialization without () in c#

In c# I used to init my class by calling default constructor. 在c#中,我曾经通过调用默认构造函数来初始化我的类。 You can mention () after class name 您可以在课程名称后提及()

var class = new MyClass()
{
   Property= 1,
   Property2 = "test"
}

But last time I see examples without () . 但是上次我看到没有()的示例。 Like this 像这样

var class = new MyClass
{
   Property= 1,
   Property2 = "test"
}

Is there any difference with and without ()? 有和没有()有什么区别吗?

There are no differences. 没有区别。 If you use resharper, it mark this () as redundant. 如果使用resharper,则将此()标记为多余。

You can use () or not, It depends on your style. 是否可以使用() ,这取决于您的样式。

This feature is called Object Initializer and it's been introduced in C#3.0. 此功能称为对象初始化器,它已在C#3.0中引入。

When you use it, the () are redundant, so there is no difference between your two code samples 使用时, ()是多余的,因此两个代码示例之间没有区别

As you see in the IL Code they are identical: 如您在IL代码中看到的,它们是相同的:

 internal class Program
    {
        public class MyClass
        {
        public int Property
        {
            get;
            set;
        }

        public string Property2
        {
            get;
            set;
        }
    }

    private static void Main(string[] args)
    {
        Program.MyClass expr_06 = new Program.MyClass();
        expr_06.Property = 1;
        expr_06.Property2 = "test";
        Program.MyClass expr_20 = new Program.MyClass();
        expr_20.Property = 1;
        expr_20.Property2 = "test";
    }
}

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

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