关于数据类型转换

代码
static void Main()
{
try
{
ArrayList array
= new ArrayList();

Console.WriteLine(
"注入int类型的数据");
int x = 12;
array.Add(x);
x
= 14;
array.Add(x);

Console.WriteLine(
" Object - INT");
foreach (object obj in array)
{
int temp = 0;

int.TryParse(obj.ToString().Trim(), out temp);

Console.WriteLine(
"obj:{0} ", temp);
}

Console.WriteLine(
" Object - LONG");
foreach (object obj in array)
{
long temp = 0;

long.TryParse(obj.ToString().Trim(), out temp);

Console.WriteLine(
"obj:{0} ", temp);
}

Console.WriteLine(
" INT ");
foreach (int obj in array)
{
Console.WriteLine(
"obj:{0} ", obj);
}

//Console.WriteLine(" LONG "); //--Error
//foreach (long obj in array)
//{
// Console.WriteLine("obj:{0} ", obj);
//}


Console.WriteLine(
"\r\n\r\n");
Console.WriteLine(
"注入long类型的数据");

long y = 20;
array.Add(y);
y
= 24;
array.Add(y);

Console.WriteLine(
" Object - INT ");
foreach (object obj in array)
{
int temp = 0;

int.TryParse(obj.ToString().Trim(), out temp);

Console.WriteLine(
"obj:{0} ", temp);
}

Console.WriteLine(
" Object - LONG ");
foreach (object obj in array)
{
long temp = 0;

long.TryParse(obj.ToString().Trim(), out temp);

Console.WriteLine(
"obj:{0} ", temp);
}

//Console.WriteLine(" LONG ");
//foreach (long obj in array) //-- Error
//{
// Console.WriteLine("obj:{0} ", obj);
//}

//Console.WriteLine(" INT ");
//foreach (int obj in array) //-- Error
//{
// Console.WriteLine("obj:{0} ", obj);
//}


}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Console.ReadLine();
}

 

上面的代码不用说简单的很,如果单独的使用C#语言或者说是在数据类型明确的情况下、进行数据类型转换使用下面的这种方式也是没有太大问题的:

代码
Console.WriteLine(" INT ");
foreach (int obj in array)
{
Console.WriteLine(
"obj:{0} ", obj);
}

Console.WriteLine(
" LONG");
foreach (long obj in array)
{
Console.WriteLine(
"obj:{0} ", obj);
}


但是如果是在额外的一些情况下:例如我遇到的利用Socket传输json, 对方发过来的数据 明明定义的是64位的,而我这里解析json时ArraryList里存放的数据却是32位的,唉…… 为了安全还是用下面的方式吧:

 

代码
Console.WriteLine(" Object - INT");
foreach (object obj in array)
{
int temp = 0;

int.TryParse(obj.ToString().Trim(), out temp);

Console.WriteLine(
"obj:{0} ", temp);
}

Console.WriteLine(
" Object - LONG");
foreach (object obj in array)
{
long temp = 0;

long.TryParse(obj.ToString().Trim(), out temp);

Console.WriteLine(
"obj:{0} ", temp);
}

 

posted @ 2010-12-03 16:06  把爱延续  阅读(455)  评论(2编辑  收藏  举报