2013-04-29 50 views
1

我回顾这段代码(C#编写):逗号在C#statament

string root = match.Groups[1].Value, 
       secon = match.Groups[2].Success ? match.Groups[2].Value.Substring(1) : string.Empty, 
       third = match.Groups[3].Success ? match.Groups[3].Value.Substring(1) : string.Empty; 

有人可以解释逗号的目的是什么?

+3

呃,这是如何*不*使用该语法的一个很好的例子。这个问题只存在,因为语法很难理解。在所有的空白处,代码实际上会被缩短*如果它是以通常的方式写入的话。 – 2013-04-29 17:07:25

+0

@TimS。是对的;这是如何滥用该功能的一个很好的例子。不过,情况可能会更糟。在Visual Basic的早期版本中,“Dim Curly,Larry,Moe as Stooge”当然意味着“Curly”和“Larry”是“Variant”,Moe是“Stooge”。 – 2013-04-29 18:25:29

回答

5

它声明了string这三个变量,分别命名为root,seconthird。就像这样:

int a, b, c; 
0

它们被用来作为一种快捷方式创建变量,并在你的榜样,所有这些都是string类型。

3

这是一个句法快捷方式。你上面的例子是语法糖,并且完全相同:

string root = match.Groups[1].Value ; 
string secon = match.Groups[2].Success ? match.Groups[2].Value.Substring(1) : string.Empty ; 
string third = match.Groups[3].Success ? match.Groups[3].Value.Substring(1) : string.Empty ; 

因此,它可以节省您一些输入。

就是这样。

+0

也可以使用'var'关键字。在这种情况下,绝不允许将多个声明与逗号放在一起。 – 2013-04-29 17:42:05

+0

@JeppeStigNielsen:有一种情况是在一个语句中用'var'放置多个声明是合法的。你能猜出这是什么? – 2013-04-29 18:24:04

+0

@EricLippert我很好奇,根据你的回答[这里](http://stackoverflow.com/a/4950600/1029916)和我对语言的理解,这是不允许的。 – NominSim 2013-04-29 18:31:30