C#new语句后的花括号有什么作用? [英] What do braces after C# new statement do?

查看:558
本文介绍了C#new语句后的花括号有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出下面的代码,position0的初始化方式和position1的初始化方式有什么区别?它们相等吗?如果没有,有什么区别?

Given the code below, what is the difference between the way position0 is initialized and the way position1 is initialized? Are they equivalent? If not, what is the difference?

class Program
{
    static void Main(string[] args)
    {
        Position position0 = new Position() { x=3, y=4 };

        Position position1 = new Position();
        position1.x = 3;
        position1.y = 4;
    }
}

struct Position
{
    public int x, y;
}

推荐答案

对象和集合初始化程序,用于初始化对象上的字段.

Object and collection initializers, used to initialize fields on an object.

http://msdn.microsoft.com/en-us/library/bb384062.aspx

它们产生接近的等效IL.乔恩·斯凯特(Jon Skeet)给出了真实情况的答案.

They produce nearly equivalent IL. Jon Skeet has the answer on what is really going on.

这篇关于C#new语句后的花括号有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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