在C#中实例化类时使用()或{}

Cra*_*ian -1 c# initializer

x1和x2的初始化有什么不同吗?

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var x1 = new C { };

            var x2 = new C ();

        }
    }

    public class C
    {
        public int A; 
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*arc 7

在你的例子中,没有区别.两者都调用默认构造函数而不传入任何值.{}是对象初始值表示法,它允许您设置未通过构造函数传递的公共属性的值.

防爆.使用以下类,PropertyA通过构造函数传入,PropertyA,PropertyB,PropertyC可在对象上设置.

class TestClass
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
    public string PropertyC { get; set; }

    public TestClass(string propertyA)
    {
        propertyA = propertyA;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要设置所有值,您可以执行此操作

var test1 = new TestClass("A");
test1.PropertyB = "B";
test1.PropertyC = "C";
Run Code Online (Sandbox Code Playgroud)

或者使用对象初始化程序格式的等价物

var test2 = new TestClass("A") {PropertyB = "B", PropertyC = "C"};
Run Code Online (Sandbox Code Playgroud)