C#中DataSet初始化的差异

kjv*_*kjv -1 c# initialization object dataset

这两种初始化对象的方法之间是否存在差异(性能,开销):

MyTypedDataSet aDataSet = new MyTypedDataSet();
aDataSet .Merge(anotherDataSet);
aDataSet .Merge(yetAnotherDataSet);
Run Code Online (Sandbox Code Playgroud)

MyTypedDataSet aDataSet = anotherDataSet;
aDataSet .Merge(yetAnotherDataSet);
Run Code Online (Sandbox Code Playgroud)

你推荐哪一个?

Kei*_*ith 5

这两行做不同的事情.

第一个创建一个新集合,然后将第二个集合合并到其中.

第二个将ds引用设置为指向第二个集合,因此:

MyTypedDataSet ds1 = new MyTypedDataSet();
ds1.Merge(anotherDataSet);
//ds1 is a copy of anotherDataSet
ds1.Tables.Add("test")

//anotherDataSet does not contain the new table

MyTypedDataSet ds2 = anotherDataSet;
//ds12 actually points to anotherDataSet
ds2.Tables.Add("test");

//anotherDataSet now contains the new table
Run Code Online (Sandbox Code Playgroud)

好吧,让我们假设你的意思是:

MyClass o1 = new MyClass();
o1.LoadFrom( /* some data */ );

//vs

MyClass o2 = new MyClass( /* some data */ );
Run Code Online (Sandbox Code Playgroud)

然后后者更好,因为前者在填充之前创建一个空对象.

然而,除非初始化空类具有高成本或重复很多次,否则差异并不重要.