預期結果 :
List<something> obj = new List<something>(); //something is i need.
string[] val = new string[] {"hi","20"}; //here I used static but input data fetch from CSV file. So we don't know when which type of data will come?.
int intval;
for(int i=0;i<val.Length;i )
{
if(int.TryParse(val[i],out intval)
{
obj.add(intval); //here I face the error "Cannot implicitly convert int to string"
}
else
{
obj.add(val[i]);
}
}
我需要將 int 值和字串值添加到同一個串列中。但條件是開發人員不知道什么時候會出現哪種型別的值。所以這里我用來TryParse轉換值并存盤到串列中。
如何宣告串列或有任何其他方法?
Note: Don't use Class to declare field and define like List<classname> val = new List<classname>();
uj5u.com熱心網友回復:
不知道你為什么要這樣做,但我認為下面的代碼就是你要找的。我想您以后可以檢查每個串列值 typeof 是否為 string/int 但為什么將多值型別存盤在這樣的一個串列中?
string[] val = new string[] { "hi", "20" };
List<object> objs = val.Select(x =>
{
if (int.TryParse(x, out var intval))
return (object)intval;
else
return (object)x;
}).ToList();
uj5u.com熱心網友回復:
如果您只需要將獲得的所有結果存盤到單個串列中而不關心型別,那么不要決議為 int 型別
for (int i = 0; i < val.Length; i )
{
//simply add the
obj.add(val[i]);
}
uj5u.com熱心網友回復:
只需使用一個List<object>. 每種型別最終都源自object:
List<object> obj = new List<object>();
string[] val = new string[] {"hi","20"};
for(int i = 0; i < val.Length; i )
{
if(int.TryParse(val[i], out var intval)
{
obj.add(intval);
}
else
{
obj.add(val[i]);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401342.html
上一篇:React-Adminwith.net.Theresponseto'getList'mustlike{data:[{id:123,...},...]},但接收到的資料項沒有
下一篇:int屬性的長度驗證
