获取对象类型并相应地分配值 [英] get object type and assign values accordingly
本文介绍了获取对象类型并相应地分配值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组列表,其中包含不同类型的值,第一个值-> 字符串,第二个值-> 日期时间,第三个值-> 布尔值,第4个值是 int ,如何找到自己的类型并相应地分配这些值,我们将为您提供帮助:)
I have an arraylist that gets different type of values in it, 1st value->string,2nd value-> datetime, 3rd value--> boolean and 4th value is int, how do I find thier type and assign those values accordingly, any help is appreciated:)
这是我的代码:
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....}
}
谢谢大家,我的最终代码:
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);
推荐答案
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();
}
}
这篇关于获取对象类型并相应地分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文