将循环变量追加到变量名 [英] Append Loop Variable to Variable Name
问题描述
我有5个数据表需要转换为TXT文件。我没有单独创建它们,而是以为我使用了 for
循环。这是我的代码:
I have 5 DataTables that needs to be converted to TXT files. Instead of creating them separately, I thought I use a for
loop. Here's my code:
StringBuilder sb = new StringBuilder();
for (int i = 1; i < 5; i++)
{
DataTable dtFile1 = file1BLO.SelectFile1ForCSV()
foreach (DataRow dr in dtFile1.Rows)
{
string[] fields = dr.ItemArray.Select(field => field.ToString()).ToArray();
sb.AppendLine(string.Join("|", fields) + "|");
}
Response.ContentType = "application/text";
Response.AddHeader("content-disposition", "attachment;filename=CAPRES-FILE1-"
+ DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".txt");
Response.Output.Write(sb);
Response.Flush();
Response.End();
sb.Clear();
}
我希望将迭代器附加到变量名和方法之后。像这样的 DataTable dtFile + i = file + i + BLO.SelectFile + i + ForCSV();
I would want the iterator to be appended to the variable names and methods. Like this DataTable dtFile + i = file + i + BLO.SelectFile + i + ForCSV();
谢谢!
SelectFile1ForCSV()的请求代码
Requested Code for SelectFile1ForCSV()
public DataTable SelectFile1ForCSV()
{
return file1DAO.SelectFile1ForCSV();
}
编辑:很抱歉,似乎我没有提供足够的详细信息,我的问题引起了混乱。立即编辑。
I am sorry, it seems that I haven't provided enough details, and my question has caused confusion. Edited now.
推荐答案
您不能只在运行时将数字附加到变量名上以神奇地引用新变量。相反,您应该做的是:
You cannot just append a number to a variable name at runtime to magically reference a new variable. What you should do instead is:
定义一个接口:
public interface IFileBLO
{
DataTable SelectFileForCSV();
}
具有 File1BLO
, File2BLO
等都实现了 IFileBLO
并修复方法名称,以使它们全部为 SelectFileForCSV
而不是 SelectFile1ForCSV
等。
Have File1BLO
, File2BLO
etc all implement IFileBLO
and fix the method names so that they are all SelectFileForCSV
rather than SelectFile1ForCSV
etc.
添加查找以引用这些对象:
Add a lookup for reference these objects:
var bloList = new IFileBLO[]
{
file1BLO, file2BLO, file3BLO, file4BLO, file5BLO
};
最后,将循环更改为:
for (int i = 0; i < 5; i++)
{
var dtFile = bloList[i].SelectFileForCSV();
foreach (var dr in dtFile.Rows)
{
...
这篇关于将循环变量追加到变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!