简单的代码改写,希望有人能帮一下.
原代码如下:
string[] Drive()
{
string[] tmpDrive = new string[5];
int tmp = 0;
DriveInfo[] allDrive = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrive)
{
if (d.DriveType == DriveType.Fixed)
{
tmpDrive[tmp] = d.ToString() ;
tmp++;
}
}
return tmpDrive;
}
如何改写才能不用创建5个元素,而是根据动态创建TMPDRIVE数组?
就是类似于一下代码:
string[] Drive()
{
string[] tmpDrive; //就是这句
int tmp = 0;
DriveInfo[] allDrive = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrive)
{
if (d.DriveType == DriveType.Fixed)
{
tmpDrive[tmp] = d.ToString() ;
tmp++;
}
}
return tmpDrive;
}
------解决方案--------------------DriveInfo[] allDrive = DriveInfo.GetDrives();
tmpDrive = new string[allDrive.Length]; //就是这句
------解决方案--------------------用这条语句试试,可以动态改变数组arrayName的长度
Array.Resize(ref arryName, length);
------解决方案--------------------楼上的正解
利用动态数组
------解决方案--------------------我的使用习惯是用List <string> drivers = new List <string> ();