简体   繁体   English

如何在C#中一次初始化多个对象

[英]how to initialize multiple objects at once in c#

I need to initialize multiple objects like this. 我需要像这样初始化多个对象。

DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataTable dt3 = new DataTable();
DataTable dt4 = new DataTable();

Is there a way to initialize them as 有没有办法将它们初始化为

DataTable dt1, dt2, dt3, dt4 = new DataTable();

If I use above, there are no compile errors but there are runtime errors says An Object reference not set to an instance. 如果我在上面使用,则没有编译错误,但有运行时错误,提示未An Object reference not set to an instance.

How can I achieve this. 我该如何实现。

No, there´s no such way, you have to initialize them one by one. 不,没有这种方法,您必须一个一个地初始化它们。

Your error appears because dt1 to dt3 are initialized to null , only dt4 has a value. 出现您的错误是因为dt1dt3初始化为null ,只有dt4有一个值。 Thus doing anything with d1 will throw a NullReferenceException . 因此,使用d1进行任何操作都会抛出NullReferenceException

But you can do so in a single line: 但是您可以单行执行此操作:

DataTable t1 = new DataTable(), t2 = new DataTable(), t3 = new DataTable(), t4 = new DataTable();

Even better would be a list/array: 更好的是列表/数组:

var tables = new[] { new DataTable(), new DataTdable(), new DataTable(), new DataTable() };

or even 甚至

var tables = Enumerable.Range(0, 4).Select(x => new DataTable());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM