2017-03-10 100 views
-4

如何将递归时间添加到timedate或时间跨度值?将日期时间值添加到以前的日期时间值

我已经试过这一点,但它给了我错误:

'A local variable named 'total' cannot be declared in this scope because it would give a different meaning to 'total, which is already in used in a 'parent or current' scope to denote something else'

private void button5_Click(object sender, EventArgs e) 
     { 
      int a = 0; 
      string path = @"C:\Users\Public\WriteLines.txt"; 
      using (StreamReader sr = new StreamReader(path)) 
      { 
       string line; 
       string[] lines = new String[500]; 

       DateTime now = DateTime.Now; 
       TimeSpan total = now - now; 
       int temp=0; 

       while ((line = sr.ReadLine()) != null) 
       { 
        lines[a] = line; 
        a++; 

       } 

       while (temp < a) 
       { 

        TimeSpan difference = Convert.ToDateTime(lines[temp+1]) - Convert.ToDateTime(lines[temp]); 
        TimeSpan total = total + difference; // <----ERROR HERE 
        Console.WriteLine(total); 
        Console.WriteLine(difference); 
        temp = temp + 2; 
       } 

      } 
     } 

也就是有没有更好的办法,以日期时间值设置为零,这样我可以递归增加值?

回答

0

你不能这样做,因为你已经有一个具有相同名称的变量,与其他一些变量名替换,

TimeSpan newTotal = total + difference; 
Console.WriteLine(newTotal); 

更好的办法是总前去除入库时间,这样你就不必再重复,

total = total + difference; 
    Console.WriteLine(total); 
3

您在方法中定义了“总数”两次。你有没有尝试从第二个定义中删除'TimeSpan'?

0

如错误所述,变量已经定义。在同一个变量的工作,或宣布一个新的与其他名字:

total = total + difference; 

TimeSpan total2 = total + difference;