private string[] ColeccionDeCortes(string Path)
{
DirectoryInfo X = new DirectoryInfo(Path);
FileInfo[] listaDeArchivos = X.GetFiles();
string[] Coleccion;
foreach (FileInfo FI in listaDeArchivos)
{
//Add the FI.Name to the Coleccion[] array,
}
return Coleccion;
}
我想把FI.Name
转换为字符串,然后把它加入我的数组。我怎样才能做到这一点?
使用System.Collections.Generic的List
List<string> myCollection = new List<string>();
…
myCollection.Add(aString);
或者,速记(使用集合初始化器)。
List<string> myCollection = new List<string> {aString, bString}
如果你真的想在最后有一个数组,可以使用
myCollection.ToArray();
你最好抽象成一个接口,比如IEnumerable,然后直接返回集合。
编辑:如果你必须使用一个数组,你可以预先将其分配到合适的大小(即你拥有的 FileInfo 的数量)。然后,在foreach循环中,为你接下来需要更新的数组索引维护一个计数器。
private string[] ColeccionDeCortes(string Path)
{
DirectoryInfo X = new DirectoryInfo(Path);
FileInfo[] listaDeArchivos = X.GetFiles();
string[] Coleccion = new string[listaDeArchivos.Length];
int i = 0;
foreach (FileInfo FI in listaDeArchivos)
{
Coleccion[i++] = FI.Name;
//Add the FI.Name to the Coleccion[] array,
}
return Coleccion;
}