2011-10-02 26 views
1

所以我有一个文本文件,如下面的解析.txt文件为不同的数据类型

-9 
5.23 
b 
99 
Magic 
1.333 
aa 

当我尝试使用下面的代码,对GetType()函数把它作为读取它读取字符串:

string stringData; 

streamReader = new StreamReader(potato.txt); 
while (streamReader.Peek() > 0) 
{ 
    data = streamReader.ReadLine(); 
    Console.WriteLine("{0,8} {1,15}", stringData, stringData.GetType()); 
} 

那么,这就是输出:

-9  System.String 
5.23 System.String 
b  System.String 
99  System.String 
Magic System.String 
1.333 System.String 
aa  System.String 

我明白,我问StreamReader类全部以字符串形式阅读。

我的问题是,一个人如何把它读作不同的不同的数据类型(如字符串,整数,双),并将其输出为:

-9  System.int 
5.23 System.double 
b  System.String 
99  System.int 
Magic System.String 
1.333 System.double 
aa  System.String 

回答

6

你必须字符串转换为类型:

string stringData; 
double d; 
int i; 

streamReader = new StreamReader(potato.txt); 
while (streamReader.Peek() > 0) 
{ 
    data = streamReader.ReadLine(); 

    if (int.TryParse(data, out i) 
    {  
     Console.WriteLine("{0,8} {1,15}", i, i.GetType()); 
    } 
    else if (double.TryParse(data, out d) 
    {  
     Console.WriteLine("{0,8} {1,15}", d, d.GetType()); 
    } 
    else Console.WriteLine("{0,8} {1,15}", data, data.GetType()); 
} 
+0

非常感谢。顺便说一句,你为什么用“out”?为什么必须通过参考来传递? – iggy2012

+0

我没有选择,tryparse方法有这个参数结构。如果你想要返回两个值的方法是一个不错的选择。 – Blau

1

通常你会知道类型(文件的结构)。

如果不是,请使用RegEx检查可能的intdouble值,其余为string