这是什么语法? [英] What is this syntax?

查看:96
本文介绍了这是什么语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

this.Add(new TabPage
{
    Text = text
});



我在反编译TabControl的源代码后看到了这一点.我可以推断出它在做什么,但我从未见过像以前那样创建过对象.



I saw this after decompiling the source for TabControl. I can sort of infer what it''s doing, but I''ve never seen an object being created like that before.

new TabPage { Text = text };

推荐答案

好了,现在您看到了.有什么特别之处? :-)

请在C#3.0规范中看到它(我相信此版本中引入了此语法):
这是与使用此功能的编码样式有关的一个非常有趣的讨论:
http://stackoverflow.com/questions/2574725/is-it-bad-to-use-initializer-block [
Well, now you see it. What''s so special about it? :-)

Please see it in the specification of C# 3.0 (I believe this syntax was introduced in this version): http://msdn.microsoft.com/en-us/library/ms364047%28v=vs.80%29.aspx#cs3spec_topic5[^], locate the section "Object Initializers".

This is a pretty funny discussion related to coding styles using this feature: http://stackoverflow.com/questions/2574725/is-it-bad-to-use-initializer-block[^].

I personally think there is nothing wrong in it, even though I understand concerns of those warning against the practice of using those block object initializers. Many language features can be abused or, just the opposite, reasonably used, depending on the situation.

—SA


实际上,在初始化后直接设置一些属性是一种捷径".
考虑一下:
Actually, it''s a ''shortcut'' to setting some Properties directly after initialization.
Consider this:
// Instead of doing:
Person p = new Person();
p.Name = "Naerling";
p.LastName = "Hell yeah!";
p.Age = 24;
// Or...
Person p = new Person() { Name = "Naerling", LastName = "Hell yeah!", Age = 24 };
// And then...
this.AddPersonToPhoneBook(p);

// You could be doing:
this.AddPersonToPhoneBook(new Person() { Name = "Naerling", LastName = "Hell yeah!", Age = 24 });


我个人从不使用这种语法.我没有理由不这样做.


Personally I never use this syntax. I have no good reason not to though.


这篇关于这是什么语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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