当我不知道上限值时,如何在使用前正确初始化该数组?
我有以下代码部分,作用于 xml 文件中的
节点中的值:
var tests = new ServicesTests();
var testcase = new TestData();
var x = 0;
foreach (XPathNavigator test in Service.Select("Testname"))
{
testcase.Testname[x] = test.Value;
x++;
}
tests.ServiceTests.Add(testcase);
对象在此处声明:
public class ServicesTests
{
public List<TestData> ServiceTests = new List<TestData>();
}
public class TestData
{
...
public string[] Testname { get; set; }
}
现在,我在尝试时收到空值引用异常设置数组。我明白为什么,但我不确定初始化它的正确方法是什么,因为我无法知道可以有多少个值。我读过的所有示例似乎都假设知道这一点..
关于如何正确完成此操作有什么建议吗?
谢谢
编辑:我更新了一些以前丢失的代码,因为使用列表仍然返回空引用错误。
I have the following section of code that acts on values in <Test></Test>
nodes from an xml file:
var tests = new ServicesTests();
var testcase = new TestData();
var x = 0;
foreach (XPathNavigator test in Service.Select("Testname"))
{
testcase.Testname[x] = test.Value;
x++;
}
tests.ServiceTests.Add(testcase);
The objects were declared here:
public class ServicesTests
{
public List<TestData> ServiceTests = new List<TestData>();
}
public class TestData
{
...
public string[] Testname { get; set; }
}
Now I receive a null value reference exception when trying to set the array. I understand why, but I'm not sure what the proper way to initialize it is, since I will have no way of knowing just how many values there can be. All the examples I've read seem to assume knowing this..
Any suggestions on how this should be done properly?
Thanks
EDIT: I updated to add some code previously missing since using a list still returns a null reference error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您需要一个可扩展的数组,则需要编写代码来管理其大小并根据需要扩展它,否则您可以使用
List
代替,并在需要时将其转换为数组重新使用ToArray()
添加项目If you need an expandable array you'll need to write code to manage its size and grow it as needed, or else you could use a
List<string>
instead and convert it to an array when you're done adding items usingToArray()
上面的好答案的例子。
Example of the above good answers.
您可能想使用通用的
List
来代替。您只需使用其Add
方法即可将内容放入其中。如果您需要一个数组,那么可以使用myList.ToArray()
轻松进行转换。You probably want to use a generic
List<string>
instead. You can just use itsAdd
method to put things into it. If you need an array when all is said and done, it's easy to convert withmyList.ToArray()
.使用 List 集合,它可以在添加值时动态调整大小,然后您可以根据需要将 List 转换为数组。
例如
Use a List collection, which can dynamically resize as you add values, then you can convert the List to an array if you need to.
e.g.
您可以使用 LINQ 在一行中完成此操作:
您甚至不需要知道数组的大小。
You can do this in one line with LINQ:
You don't even need to know the size of the array either.