c#字符串到变量
本文关键字:变量 字符串 | 更新日期: 2023-09-27 18:06:52
我想使用字符串作为变量( string + int = variable )
public DataTable Add_new(string t1,string t2,string t3,string t4,
string t5,string t6,string t7,string t8,
string t9,string t10)
{
OleDbParameter[] param = new OleDbParameter[10];
for (int i = 1; i < 11; i++)
{
param[i-1] = new OleDbParameter(""+i+"", OleDbType.VarChar);
param[i-1].Value = ("t"+i);
}
DataTable dt = new DataTable();
dt = DAL.selectdata("Add_Code", param);
return dt;
}
您可以将值放入数组中,然后您可以通过索引访问它们:
public DataTable Add_new(string t1,string t2,string t3,string t4,string t5,string t6,string t7,string t8,string t9,string t10) {
string[] t = { t1, t2, t3, t4, t5, t6, t7, t8, t9, t10 };
OleDbParameter[] param = new OleDbParameter[10];
for (int i = 1; i < 11; i++) {
param[i-1] = new OleDbParameter(i.ToString(), OleDbType.VarChar);
param[i-1].Value = (t[i - 1]);
}
DataTable dt = new DataTable();
dt = DAL.selectdata("Add_Code", param);
return dt;
}
另一种方法是将参数转换为params
数组。你可以用同样的方式调用它,但是当它到达时它是一个数组:
public DataTable Add_new(params string[] t) {
if (t.Length != 10) throw new ArgumentsException("The method should be called with 10 parameters.");
OleDbParameter[] param = new OleDbParameter[10];
for (int i = 1; i < 11; i++) {
param[i-1] = new OleDbParameter(i.ToString(), OleDbType.VarChar);
param[i-1].Value = (t[i - 1]);
}
DataTable dt = new DataTable();
dt = DAL.selectdata("Add_Code", param);
return dt;
}
注意:你发送到方法中的那些值可能有一些含义。您应该考虑为参数取一个有意义的名字,并且可能只编写用于创建十个参数的代码。用一个循环来做这件事很方便,但是维护起来并不容易。
为什么不把它作为a传递呢:
List<String> T;
代替
string t1,string t2,string t3,string t4,string t5,string t6,string t7,string t8,string t9,string t10
然后:
for (int i = 1; i < 11; i++)
{
param[i-1] = new OleDbParameter(""+i+"", OleDbType.VarChar);
param[i-1].Value = (T[i-1]);
}
就是
public DataTable Add_new(List<String> T) {
OleDbParameter[] param = new OleDbParameter[10];
for (int i = 1; i < 11; i++) {
param[i-1] = new OleDbParameter(i.ToString(), OleDbType.VarChar);
param[i-1].Value = (T[i-1]);
}
DataTable dt = new DataTable();
dt = DAL.selectdata("Add_Code", param);
return dt;
}
你的实现没有意义。无论如何,以下内容都可以满足您的请求。
public DataTable Add_new(string t1, string t2, string t3, string t4,
string t5, string t6, string t7, string t8,
string t9, string t10)
{
OleDbParameter[] param = new OleDbParameter[10];
for (int i = 1; i < 11; i++)
{
param[i - 1] = new OleDbParameter("" + i + "", OleDbType.VarChar);
switch("t" + i)
{
case "t1":
param[i - 1].Value = t1;
break;
case "t2":
param[i - 1].Value = t2;
break;
//Recreate up to t10
}
}
DataTable dt = new DataTable();
dt = DAL.selectdata("Add_Code", param);
return dt;
}
试试这个
public DataTable Add_new(params string[] t)
{
OleDbParameter[] param = new OleDbParameter[10];
for (int i = 0; i <= 10; i++)
{
var paramName = String.Format("t{0}", i+1);
param[i] = new OleDbParameter(paramName, OleDbType.VarChar);
param[i].Value = (t[i]);
}
DataTable dt = new DataTable();
dt = DAL.selectdata("Add_Code", param);
return dt;
}