Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将.txt文件解析为不同的数据类型_C#_Parsing_Types_Casting - Fatal编程技术网

C# 将.txt文件解析为不同的数据类型

C# 将.txt文件解析为不同的数据类型,c#,parsing,types,casting,C#,Parsing,Types,Casting,我有一个文本文件,如下所示 -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

我有一个文本文件,如下所示

-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类将其全部作为字符串读取

我的问题是,如何将其读取为不同的数据类型,即string、int、double,并将其输出为:

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

您必须将字符串转换为以下类型:

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());
}

您必须将字符串转换为以下类型:

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());
}

通常,您会知道文件的类型和结构


如果不是,则使用正则表达式检查可能的int和double值,其余的作为字符串返回

通常您会知道文件的类型和结构


如果不是,则使用正则表达式检查可能的int和double值,其余的作为字符串返回

非常感谢。顺便问一下,你为什么用光了?为什么它必须通过引用传递?我没有选择,tryparse方法有那个参数结构。如果您希望方法返回两个值,这是一个不错的选择。非常感谢。顺便问一下,你为什么用光了?为什么它必须通过引用传递?我没有选择,tryparse方法有那个参数结构。若您希望方法返回两个值,那个么这是一个不错的选择。