c# - 如何创建消除重复代码的函数

标签 c# asp.net arrays

我的 Page_Load 函数中有以下代码:

string[] strArrayForEntity;
string[] strArrayForLocation;
string[] strArrayForSpecialty;
int inCounter;
inCounter = 0;

strArrayForEntity = new string[Entity.Items.Count];
foreach (ListItem li in Entity.Items)
{
    strArrayForEntity[inCounter] = li.Value;
    inCounter++;
}

inCounter = 0;
strArrayForLocation = new string[Location.Items.Count];
foreach (ListItem li in Location.Items)
{
    strArrayForLocation[inCounter] = li.Value;
    inCounter++;
}

inCounter = 0;
strArrayForSpecialty = new string[Specialty.Items.Count];
foreach (ListItem li in Specialty.Items)
{
    strArrayForSpecialty[inCounter] = li.Value;
    inCounter++;
}

如您所见,除了数组名称和下拉列表 ID 之外,我重复了同样的事情。

我想创建一个函数,我可以在其中提供数组名称和下拉列表,这样我就不必重复代码了。我尝试了以下方法:

public void AddTooArray(string[] strArrayName, DropDownList strID)
{
    inCounter = 0;
    foreach (ListItem li in strID.Items)
    {
        strArrayName = li.Value;
        inCounter++;
    }
}

我打算这样调用它:AddToArray(strArrayForEntity, Entity);

我在这一行中收到错误:strArrayName = li.value; 错误:无法将类型“string”隐式转换为“string[]”

我能解决这个问题吗?

测试代码:

protected void Page_Load(object sender, EventArgs e)
{
    strArrayForEntity = new string[Entity.Items.Count]; //count is 1 (2 entries in the dropdownlist)
    AddToArray(strArrayForEntity, Entity);
    MessageBox.Show(strArrayForEntity.Length.toString()); //displays 0
}
public void AddToArray(string[] strArrayName, DropDownList strID)
{
    inCounter = 0;
    foreach (ListItem li in strID.Items)
    {
        strArrayName[inCounter] = li.Value;
        inCounter++;
    }
}

最佳答案

您忘记了数组索引器。

strArrayName[inCounter] = li.Value;

关于c# - 如何创建消除重复代码的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28049760/

相关文章:

Python(scipy)从文本文件导入时间

c# - TCPClient套接字错误0x80004005的原因

asp.net - Hangfire 如何为网络农场工作?

PHP - 如何将查询结果放入数组中?

javascript - 无法从 td 获取文本(ASP.NET MVC)

asp.net - 两种类型的 asp.net 核心 Web 应用程序?

c - 将数组传递给函数

c# - Compact Framework/Threading - MessageBox 在选择选项后显示在其他控件之上

c# - 使用 Selenium 使用 WindowHandles 跟踪和遍历选项卡和窗口的最佳方法

c# - Waitform 上的进度条使用在另一个线程上运行的任务卡住