我有一个arraylist,其中包含不同类型的值,第一个值 - > 字符串,第二个值 - > datetime,第三个值 - > 布尔值和第四个值是int,我如何找到它们的类型并相应地分配这些值,任何感谢帮助:)
这是我的代码:
foreach (object obj in lstTop)
{
if(obj.GetType() == string)
{do this...)
else if(obj.GetType() == DateTime)
{do this....}
else if(obj.GetType() == bool)
{do this....}
else if(obj.GetType() == Int)
{do this....}
}
Run Code Online (Sandbox Code Playgroud)
谢谢大家,我的最终守则:
string Subscription = "";
DateTime issueFirst;
DateTime issueEnd;
foreach (object obj in lstTop)
{
///Type t = obj.GetType();
if (obj is string)
Subscription += obj + ",";
else if (obj is DateTime)
{
Subscription += Convert.ToDateTime(obj).ToShortDateString() + ",";
}
/// else if (t == typeof(DateTime))
}
return ("User Authenticated user name: " + userName + ", Subscription: " + Subscription);
Run Code Online (Sandbox Code Playgroud)
foreach (object obj in lstTop)
{
if(obj is string)
{do this.....}
else if(obj is DateTime)
{do this.....}
else if(obj is bool)
{do this.....}
else if(obj is Int)
{do this.....}
else
{
// always have an else in case it falls through
throw new Exception();
}
}
Run Code Online (Sandbox Code Playgroud)