近期在学习一个别人写的代码,看到一段关于http头部数据拷贝的语句,但是用法实在奇怪,没见过此类语法。
主要代码如下:
private WebHeaderCollection _header;
//由于传递过去的Headers的值可能发生变化,所以这里需要完全拷贝一份。
WebHeaderCollection tmpHeader = new WebHeaderCollection { _header };
http.Headers = tmpHeader;
_header对象在申明以后,还有一些赋值操作,这里省略了,没有写出来。代码中的注释是本来就有的注释,说明该语句用于对_header进行数据拷贝,但是此类new语法我看不懂,不像是调用WebHeaderCollection的构造函数,也不像匿名类,因为有类名。
求解?
我知道了,刚才看错了。
这个是集合初始化器
相当于
WebHeaderCollection tmpHeader = new WebHeaderCollection();
tmpHeader.Add(_header);
你可以自己做一个实验。新建一个控制台程序,编写如下代码:
using System;
class A : System.Collections.IEnumerable
{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return null;
}
public void Add(string s)
{
Console.WriteLine("add " + s);
}
}
public class Test
{
public static void Main()
{
// your code goes here
A a = new A{ "hello", "world "};
}
}
add hello
add world
应该就是拷贝构造函数。为什么你觉得“不像是调用WebHeaderCollection的构造函数”。
很明显,这段代码等价:
using System;
class A : System.Collections.IEnumerable
{
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return null;
}
public void Add(string s)
{
Console.WriteLine("add " + s);
}
}
public class Test
{
public static void Main()
{
// your code goes here
A a = new A();
a.Add("hello");
a.Add("world ");
}
}