C# 如何在函数中将列表作为参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13993371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to pass list as parameter in function
提问by TheCode
I have taken a list and insert some value in it
我取了一个列表并在其中插入了一些值
public List<DateTime> dates = new List<DateTime>();
DateTime dt1 = DateTime.Parse(12/1/2012);
DateTime dt2 = DateTime.Parse(12/6/2012);
if (dt1 <= dt2)
{
for (DateTime dt = dt1; dt <= dt2; dt = dt.AddDays(1))
{
dates.Add(dt);
}
}
Now I want pass this List i.e dates as a parameter to some function like-
现在我想将此列表即日期作为参数传递给某些函数,例如-
somefunction(dates);
How exactly can i achieve this?
我究竟如何才能做到这一点?
采纳答案by Adil
You need to do it like this,
你需要这样做,
void Yourfunction(List<DateTime> dates )
{
}
回答by Zbigniew
public void SomeMethod(List<DateTime> dates)
{
// do something
}
回答by Jakub Konecki
You can pass it as a List<DateTime>
您可以将其作为 List<DateTime>
public void somefunction(List<DateTime> dates)
{
}
However, it's better to use the most generic (as in general, base) interface possible, so I would use
但是,最好使用最通用的(一般来说,基本)接口,所以我会使用
public void somefunction(IEnumerable<DateTime> dates)
{
}
or
或者
public void somefunction(ICollection<DateTime> dates)
{
}
You might also want to call .AsReadOnly()
before passing the list to the method if you don't want the method to modify the list - add or remove elements.
.AsReadOnly()
如果您不希望方法修改列表 - 添加或删除元素,您可能还想在将列表传递给方法之前调用。
回答by a_m_dev
I need this for Unityin C# so I thought that it might be useful for some one. This is an example of passing a list of AudioSources to whatever function you want:
我在 C# 中需要这个用于Unity,所以我认为它可能对某些人有用。这是将 AudioSources 列表传递给您想要的任何函数的示例:
private void ChooseClip(GameObject audioSourceGameObject , List<AudioClip> sources) {
audioSourceGameObject.GetComponent<AudioSource> ().clip = sources [0];
}
回答by Robi Kálmán
You should always avoid using List<T>
as a parameter. Not only because this pattern reduces the opportunities of the caller to store the data in a different kind of collection, but also the caller has to convert the data into a List
first.
您应该始终避免使用List<T>
作为参数。不仅因为这种模式减少了调用者将数据存储在不同类型的集合中的机会,而且调用者必须将数据转换为List
第一个。
Converting an IEnumerable
into a List
costs O(n) complexity which is absolutely unneccessary. And it also creates a new object.
将 anIEnumerable
转换为List
O(n) 复杂度,这是绝对不必要的。它还创建了一个新对象。
TL;DR you should always use a proper interface like IEnumerable
or IQueryable
based on what do you want to do with your collection. ;)
TL;DR 您应该始终使用适当的界面,例如IEnumerable
或IQueryable
基于您想对您的收藏做什么。;)
In your case:
在你的情况下:
public void foo(IEnumerable<DateTime> dateTimes)
{
}