如何将内容添加到列表 [英] How do I add things to a list
问题描述
List<string> _otherList = new List<string>()
{
"carrot",
"banana"
};
在上面的代码中,我完全按照在网上找到该列表的方式初始化了一个列表.但是它表现出诸如此类的错误;预期为什么?
我的意图是希望该新列表具有一些初始值,以便可以通过在其上调用其add方法在其上添加内容,以便它不会抛出空值.
因此,我该怎么做才能用其添加方法(_otherList.add)调用此列表,以使在我调用其添加方法时不会调用此空列表或空列表.
In the above code I initialize a list exactly the same way i found this online.i mean some one put this one online. but its showing errors like ; expected why?
My intention is that I want to have this newlist to have some initial value so that I can add things on it by invoking its add method on it,so that it wont throw a null exeption.
So what do I do to invoke this list with its add method( _otherList.add) in a way that this empty or null list is not getting called when i call its add method.
推荐答案
我不确定我是否理解您的问题,但是为避免null异常,您要做的就是初始化列表:
I''m not sure I understand your question, but all you have to do to avoid the null exception is initialize the list:
public class MyClass
{
private List<string> _otherList = new List<string>();
public MyClass()
{
}
}
之后,您可以随时拨打_otherList.Add()
.
After that, you can call _otherList.Add()
whenever you want to.
这篇关于如何将内容添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!