列表C# 添加方法
据我所知。列表添加方法的工作原理如下。
List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
如果我将数据结构设计为这样,
List<object> lstObj = new List<object>();
if (true) // string members
{
cities.Add("New York");
cities.Add("Istanbul");
}
else // List obj members here
{
List<object> AListObject= new List<object>();
cities.Add(AListObject); // how to handle this?
}
如果我在同一函数中添加不同类型的成员,List Add
方法是否有效。
As I know. List Add method works as below.
List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
If I designed the data structure as this
List<object> lstObj = new List<object>();
if (true) // string members
{
cities.Add("New York");
cities.Add("Istanbul");
}
else // List obj members here
{
List<object> AListObject= new List<object>();
cities.Add(AListObject); // how to handle this?
}
Does the List Add
method works or not if I add different types members in the same function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您无法将
List
但这似乎是一个糟糕的设计。当您使用
object
作为集合的泛型类型时,您实际上失去了类型安全的所有好处。为了解析 XML,我建议您查看 XmlDocument 。
You can't add a
List<object>
to aList<string>
. The only thing you can add to list of strings is strings (or null references). You could use this instead:But this seems like a bad design. When you use
object
as the generic type of a collection you effectively lose all the benefits of type-safety.For parsing XML I'd suggest you look at XmlDocument.
由于您创建了一个
object
类型的列表,因此您可以向其中添加任何内容,因为每种类型都可以装箱到一个对象中。Since you created a list of type
object
you can add anything to it since every type can be boxed into an object.您可以向
List
话虽如此,无论您想要做什么,这几乎肯定是一种糟糕的编码方式。
You can add anything to a
List<object>
, so if you changedcities
to aList<object>
then your code would work.Having said that, it's almost certainly a bad way to code whatever it is you're trying to do.
如果您可以使用 .NET 3.5 中的 LINQ,那么您可以执行以下操作:
If you could use LINQ from .NET 3.5 than you could do next:
使用以对象作为类型参数的通用列表是没有意义的,还不如使用 System.Collections.ArrayList。
There's no point using a generic list with object as the type parameter, might as well use a System.Collections.ArrayList.
您应该使用 List.AddRange将多个项目添加到列表的方法。
但是,尝试将
object
添加到string
列表时会遇到问题。You should use the List.AddRange method for adding multiple items to a list.
However, you'll have problems trying to add
object
to a list ofstring
.