列表的添加和追加方法之间的区别? [英] Difference between a List's Add and Append method?

查看:48
本文介绍了列表的添加和追加方法之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#中的列表的 .Append() .Add()方法之间是否有区别?我曾尝试在Google和网站中进行搜索,但令我惊讶的是没有人问过.我问的原因是要知道这两种方法之一是否需要较少的性能.我一直在交替使用这两种方法,但是它们的功能都没有发现任何差异,因为它们都将我的对象添加到了列表的末尾(这或多或少是Visual Studio在查看功能时给您的描述方法说明).

Is there a difference between the .Append() and the .Add() method for lists in C#? I tried searching in Google and in the site but to my surprise no one asked it. My reason for asking is to know if one of the two methods are less performance intensive. I've been using the two methods interchangeably and I didn't see any differences to their function as they both added my object to the end of the list (and this is more or less the description visual studio gives you when you look at the method description).

嗯,我最初并不认为这很重要,但是当我不能在控制台应用程序上使用Append时,我注意到可以在ASP.NET Web应用程序上使用Append.因此,我是在ASP.NET Web应用程序的上下文中询问的.

Hmmm I didn't think this mattered at first but I noticed I can use Append on an ASP.NET web application when I can't do that on a console application. So I was asking in the context of an ASP.NET Web App.

推荐答案

List< T> 仅具有

List<T> in C# only has the void Add(T item) method to modify the instance add a single item to the list.

IEnumerable< T>另一方面,Append(此IEnumerable 源,T元素) 是在 IEnumerable 接口(由所有列表实现)上定义的扩展方法.).它不会修改原始列表实例,但会返回一个新的可枚举值,该值将在序列末尾产生指定的元素.

IEnumerable<T> Append(this IEnumerable<T> source, T element) on the other hand is an extension method defined on the IEnumerable<T> interface (which is implemented by all lists). It does not modify the original list instance, but returns a new enumerable which will yield the specified element at the end of the sequence.

它们不能互换使用,并且具有不同的结果和不同的副作用.这样问他们的相对表现是没有道理的.

They cannot be used interchangably and behave differently with different outcomes and different side effects. Asking about their relative performance does not make sense as such.

var list = new List<string>();
list.Add("one");
list.Add("two");
// list contains: [ one, two ]

list.Append("three");
// list still contains: [ one, two ]

这篇关于列表的添加和追加方法之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆